Certain ECMAScript statements (empty statement,variable statement,expression statement,do-while statement,continue statement,break statement,return statement,and throw statement) must be terminated with semicolons. Such semicolons may always appear explicitly in the source text. For convenience,however,such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.
大概可以这么理解:
解析引擎是怎么自动插入分号的?
-
左到右解析程序,当遇到一个不符合任何文法产生式的 token(叫做 违规 token(offending token)),那么只要满足下面条件之一就在违规 token 前面自动插入分号。
至少一个 LineTerminator 分割了违规 token 和前一个 token。
违规 token 是 }。
左到右解析程序,tokens 输入流已经结束,当解析器无法将输入 token 流解析成单个完整 ECMAScript 程序 ,那么就在输入流的结束位置自动插入分号。
左到右解析程序,遇到一个某些文法产生式允许的 token,但是此产生式是受限产生式,受限产生式的里紧跟在 no LineTerminator here 后的第一个终结符或非终结符的 token 叫做受限的 token,当至少一个 LineTerminator 分割了受限的 token 和前一个 token,那么就在受限 token 前面自动插入分号。
有一个附加的优先条件:如果插入分号后解析结果是空语句,或如果插入分号后它成为 for 语句头部的两个分号之一(见 12.6.3),那么不会自动插入分号
结论
搞清楚了原理,加或者不加,其实变得不那么重要了。
只要在团队中,选择一种风格一以贯之。