An expression produces a value whereas a statement will not.
All statements in JavaScript must end with a semi-colon, to indicate that this is where the statement ends.
The parser may add semicolon if it encounter a parse error. See below Automatic semicolon insertion
The statement
b
(2);
is equivalent to
b(2);
statements can be grouped in a block
Ther parser infers omitted semicolons in certain contexts, effectively “inserting” the missing semicolon into the program for you automatically. The ECMAScript standard precisely specifies the semicolon insertion mechanism.
Parser Rules:
To avoid an unwanted automatic semicolon insertion problem, you can prefix statements beginning with (, [, +, -, or / with an extra semicolon.
Except that semicolons are never inserted as separators in the head of a for loop or as empty statements.
Where no newline is allowed to appear between two tokens, Javascript will insert a semicolon thanks to the restricted productions
The restricted productions are:
Example with:
function returnValueOnSameLine(){
return 4;
}
function returnValueOnNextLine(){
return // The javascript parser will add here a semicolon because the return keyword is not allowed to spread on multi-line.
4;
}
console.log(returnValueOnSameLine());
console.log(returnValueOnNextLine());
a=0;
b=0;
a
// As the suffix cannot be preceded by a new line, ++ will be a prefix and the parser add here a semicolon
++
b
console.log(a);
console.log(b);