Home >Web Front-end >JS Tutorial >Does JavaScript's Automatic Semicolon Insertion Always Prevent Errors?
Clarifying ASI's Applicability
Automatic semicolon insertion (ASI) is a JavaScript feature that automatically inserts a semicolon into the code when it is missing and would not cause syntactic errors. However, it only applies to specific statement types:
ASI Rules as per ECMAScript Specification
The ECMAScript specification defines three scenarios for ASI:
1. Invalid Token Encountered
An offending token not permitted by the grammar triggers semicolon insertion if:
2. End of Input Stream
If the input stream ends without the parser being able to parse a complete program, a semicolon is inserted at the end.
3. Restricted Productions
When a token is allowed but belongs to a "restricted production" (e.g., return or continue without a line break), a semicolon is inserted before it.
Example:
return "something";
is transformed to:
return; "something";
Exception to the Rule
However, there is an exception to the rules. If the ASI would result in a SyntaxError, it is not inserted. For instance, in the following code:
if (x) return y;
ASI would transform it to:
if (x) return; y;
This would cause a SyntaxError because y is not a valid statement on its own.
The above is the detailed content of Does JavaScript's Automatic Semicolon Insertion Always Prevent Errors?. For more information, please follow other related articles on the PHP Chinese website!