Skip to content Skip to sidebar Skip to footer

What Are The Criteria For Automatic Semicolon Insertion?

Possible Duplicate: What are the rules for Javascript's automatic semicolon insertion? JavaScript befuddles me with its implicit line termination. It's a very C-like language, e

Solution 1:

The ECMA specification (ch. 7.9.1, page 26) states:

There are three basic rules of semicolon insertion:

  1. When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true: • The offending token is separated from the previous token by at least one LineTerminator. • The offending token is }.
  2. When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript Program, then a semicolon is automatically inserted at the end of the input stream.
  3. When, as the program is parsed from left to right, a 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 “[no LineTerminator here]” within the restricted production (and therefore such a token is called a restricted token), and the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.

I think this implementation has to do with the second point where:

var x = 1 + 2-3 + 3 == 0 ? alert('0') : alert('3')

can be parsed as a single complete ECMAScript Program

Because it's not always clear how the parser will insert semi-colons, it's advisable to not leave it to the parser (i.e. always insert the semi-colons yourself).

In ch. 7.9.2 (Examples of Automatic Semicolon Insertion) of the same specs this example looks like your situation:

The source

a = b + c  
(d + e).print()

is not transformed by automatic semicolon insertion, because the parenthesised expression that begins the second line can be interpreted as an argument list for a function call: a = b + c(d + e).print()

Solution 2:

Don't leave it to the compiler, always put semicolons at the end of statements.

Post a Comment for "What Are The Criteria For Automatic Semicolon Insertion?"