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:

<html>
<!-- Semicolon_Insertion.html
   Copyright (c) 2002 HerongYang.com. All Rights Reserved.
-->
<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.

Table of Contents

 About This Book

 Introduction to JavaScript

ECMAScript Language Specification and JavaScript Dialects

 JavaScript History and Versions

 ECMAScript Language Specification

Automatic Semicolon Insertion to End Statements

 Data Types, Variables and Expressions

 Flow Control Statements

 Creating, Accessing, and Manipulating Arrays

 Defining and Calling Functions

 Web Browser Supporting JavaScript

 Server-Side and Client-Side Web Scripting

 Introduction to Objects

 Defining Your Own Object Types

 Inheritance of Properties and Methods through the Prototype Object Chain

 'jrunscript' - JavaScript Shell Command from JDK

 Using Functions as "Function" Objects

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications

 AJAX (Asynchronous JavaScript And XML)

 References

 Full Version in PDF/EPUB