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:
The offending token is separated from the previous token by at least one LineTerminator.
The offending token is }.
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:
<html>
<!-- Semicolon_Insertion.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head><title>Semicolon Insertion Rule</title></head>
<body>
<pre>
<script type="text/javascript">
document.writeln("Gravity: "+getGravity());
document.writeln("Pi: "+getPi());
function getGravity() {
return 9.8;
}
function getPi() {
// Semicolon will be inserted automatically after "return"
return
3.14159;
}
</script>
</pre>
</body>
</html>
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.