JavaScript写不写分号情景分析

757 阅读2分钟

加不加分号争论已久,最初的设计是为了降低编译器的工作负担。

自动插入分号规则

  • 规则1: 要有换行符,且下一个符号是不符合语法的,那么就尝试插入分号。
  • 规则2: 有换行符, 且语法中规定此处不能有换行符,那么自动插入分号。
  • 规则3: 源代码结束处,不能形成完整的脚本或者模块结构,那么就自动插入分号。

规则1举例

1 let a = 1
2 void funtion(a) {
3     console.log(a)
4 }(a)

在这个例子中,void跟在a=1后面是不符合语法的,所以就会命中规则1,插入分号。

no LineTerminator here规则

该规则表明它所在的结构中的这一位置不能插入换行符。

  • 带标签的continue语句,不能在continue后插入换行
  • 带标签的break 语句,不能在break后插入换行
  • reutrn后不能插入换行
  • 后自增,后自减运算符前不能插入换行
  • throw和Exception之间不能插入换行
  • 凡事async关键字,后面不能插入换行
  • 箭头函数的箭头前,不能插入换行
  • yield之后,不能插入换行

规则2 结合no LineTerminator here规则

outer: for (var j = 0; j < 10; j++)
    for (var i = 0; i < j; i++)
        continue /* no LineTerminator here*/

带标签的continue语句不能在continue后面插入换行

function f() {
    return  /* no LineTerminator here*/
}

return

i /* no LineTerminator here*/++
i /* no LineTerminator here*/--

自增自减 throw /* no LineTerminator here*/new Exception("error") throw Exception

async/* no LineTerminator here*/function f() {
    
}
const f = async/* no LineTerminator here*/x => x * x

async关键字 const f = x/* no LineTerminator here*/=> x * x 箭头函数

function *g() {
    var i = 0;
    while(true) 
        yield /* no LineTerminator here*/i++;
}
1 var a = 1, b = 1, c = 1;
2 a
3 ++
4 b
5 ++
6 c

如上规则,第二行 最后加上分号。所以结果是 a = 1, b = 2, c = 2。

不写分号需要注意的情况

以括号开头的语句

连续两个IIFE容易引起问题,建议在IIFE行首加分号

数组开头的语句

[ ]

正则表达式开头的语句

/()/g

Template开头的语句

` Template ${test}`

参考: 重学前端是程劭非(winter)【前手机淘宝前端负责人】在极客时间开的一个专栏, 每天10分钟,重构你的前端知识体系