Automatic semicolon insertion (ASI) is a feature of JavaScript that automatically adds semicolons at specific points in the code. Understanding the rules for ASI is crucial to prevent potential bugs.
Statements Affected by ASI
The following statements are affected by ASI:
ASI Rules
ASI is applied in three main cases:
Invalid Token: When an unexpected token is encountered, a semicolon is inserted before it if:
Restricted Tokens: Semicolons are automatically inserted before tokens that follow restricted productions in the grammar. This includes tokens without line terminators:
Example 1 (Invalid Token):
{ 1 2 } 3
ASI transforms this code into:
{ 1 ;2 ;} 3;
Example 2 (End of Input Stream):
a = b ++c
ASI adds a semicolon at the end:
a = b; ++c;
Example 3 (Restricted Token):
return "something";
ASI inserts a semicolon before the restricted return token:
return; "something";
Note: While ASI can provide convenience, it's important to be aware of its potential impact and to use semicolons explicitly for clarity and consistency.
The above is the detailed content of How Does JavaScript's Automatic Semicolon Insertion (ASI) Work: Rules and Exceptions?. For more information, please follow other related articles on the PHP Chinese website!