Automatic Semicolon Insertion to End Statements
This section provides the automatic semicolon insertion rule supported by the ECMAScript specification. A tutorial example is provided to show you a problem when writing 'return' in a line by itself.
ECMAScript has very interesting rule for automatic semicolon insertion to end statements. Here is how the specification describes this rule:
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.
The first situation is 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:
Other situations are listed in the specification.
The Automatic Semicolon Insertion rule is very nice in many cases. But in some cases, it could cause problems. See the following interesting example:
If you run this script in a Web browser, you will get:
Gravity: 9.8 Pi: undefined
This is very bad. So do not write "return" in a line by itself.
Table of Contents