Are semicolons mandatory in javascript statements?
Semicolons are not always mandatory, but I would always recommend using them. See the ECMAScript spec for the rules on automatic semicolon insertion:
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.
Update (to explain further)
Perhaps the most common situation used to show why automatic semicolon insertion can be bad is that touched on by @sissonb in another answer. Consider the following:
function something(a, b) {
return
a + b;
}
What you may be expecting is for the new-line to be ignored, and the code interpreted as:
function something(a, b) {
return a + b;
}
Unfortunately, automatic semicolon insertion comes into play, and the code is actually interpreted like this:
function something(a, b) {
return;
a + b;
}
And an empty return
statement means the function returns undefined
. So instead of a nice sum of the two argument, you get undefined
and potentially end up very confused as to where you've gone wrong! Which is why I completely agree with the statement in your question that automatic semicolon insertion is a horrible misfeature.
- Example (returns
undefined
because of ASI). - Example (returns expected result).