標籤:javascript 語句分號的必要性
Statements in ECMAScript are terminated by a semicolon, though omitting the semicolon makes
the parser determine where the end of a statement occurs, as in the following examples:
var sum = a + b //valid even without a semicolon - not recommendedvar diff = a - b; //valid - preferred
Even though a semicolon is not required at the end of statements, it is recommended to always
include one. Including semicolons helps prevent errors of omission, such as not finishing what you
were typing, and allows developers to compress ECMAScript code by removing extra white space
(such compression causes syntax errors when lines do not end in a semicolon). Including semicolons
also improves performance in certain situations, because parsers try to correct syntax errors by
inserting semicolons where they appear to belong.
比如下面代碼:
"use strict"function f(a, b) { return a | b ;}console.log(f(2, 1));
輸出:
所以,我們還是不要讓解析器猜測我們的用意,畢竟解析器不是人工智慧的:
正確寫法:
JavaScript 語句分號的必要性