What are the rules for JavaScript's automatic semicolon insertion (ASI)?

JavaScript’s automatic semicolon insertion (ASI) is to insert missing semicolons. The following statements are affected by automatic semicolon insertion −

empty statement
var statement
expression statement
do-while statement
continue statement
break statement
return statement
 throw statement

The rules are in the following specification −

  • When, as a Script or Module is parsed from left to right: A token is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token only if one or more of the following conditions becomes true −
  • Offending token is }.
  • Previous token is ) and the inserted semicolon would then be parsed as the terminating semicolon of a do-while statement (13.7.2).
  • End of the input stream of tokens is encountered and therefore parser is unable to parse the input token stream as a one complete ECMAScript or a Module, then a semicolon is automatically inserted.
  • Token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation.