JavaScript/Automatic semicolon insertion
Automatic Semicolon Insertion (ASI)
In languages of the C-family, the semicolon denotes the end of a statement. Unlike other C-like languages, JavaScript doesn't enforce that. Instead, the semicolon is optional, and the interpreter adds missing semicolons - mostly at the end of a line - to terminate statements. Doing so, it takes complex rules into account. This may conflict with the intended purpose.
If you write your code without semicolons at the end of statements you must take care of problematic situations. Here are some rules-of-thumb to avoid problems. But there are many more rules.
- The expression after one of the keywords
return
,throw
, oryield
must be on the same line as the keyword itself. - The label identifier after
break
orcontinue
must be on the same line as the keyword. - If a line starts with one of
(
,[
,`
,+
,-
, or/
, end the previous line with a semicolon.
Examples
Entered code .. | .. interpreted as | intended code |
---|---|---|
return
2a + 1
|
return;
2a + 1;
|
return 2*a + 1;
|
function getObject() {
return
{
// some lines
}
}
|
function getObject() {
return;
{
// some lines
};
}
|
function getObject() {
return {
// some lines
};
}
|
i
++
|
i;
++;
|
i++;
|
In the first case, the programmer intended 2*a + 1 to be returned; instead, the code returned undefined
. Similarly, in the second case, the programmer intended to return the lines enclosed by the braces {}
, but the code returned undefined
. Due to this oddity in JavaScript, it is considered a best practice never to have lines break within a statement and never have the opening brace on a separate line.