Home >Web Front-end >JS Tutorial >How Does JavaScript's Automatic Semicolon Insertion (ASI) Work and When Does it Insert Semicolons?

How Does JavaScript's Automatic Semicolon Insertion (ASI) Work and When Does it Insert Semicolons?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-23 00:17:15557browse

How Does JavaScript's Automatic Semicolon Insertion (ASI) Work and When Does it Insert Semicolons?

JavaScript's Automatic Semicolon Insertion (ASI) Rules

Automatic semicolon insertion (ASI) is a feature in JavaScript that inserts a semicolon at the end of certain statements when it is omitted. Understanding the rules of ASI is crucial to prevent unexpected behavior and bugs.

Affected Statements:

ASI applies to the following statements:

  • Empty statements
  • Var statements
  • Expression statements
  • Do-while statements
  • Continue statements
  • Break statements
  • Return statements
  • Throw statements

ASI Rules:

The rules of ASI are defined in the JavaScript specification as follows:

  • Invalid Token: If an invalid token is encountered, a semicolon is inserted before it if it is preceded by a line break and is followed by a closing curly brace.
  • Input Stream End: If the end of the input stream is reached, a semicolon is inserted if the input cannot be parsed as a complete program.
  • Restricted Tokens: Semicolons are automatically inserted before certain restricted tokens, regardless of line breaks. These include increment, decrement, continue, break, return, throw, arrow functions, and yield expressions.

Examples:

Example with Invalid Token:

{ 1
2 } 3

ASI inserts semicolons:

{ 1
;2 ;} 3;

Example with Input Stream End:

a = b
++c

ASI inserts a semicolon:

a = b;
++c;

Example with Restricted Token:

return
"something";

ASI inserts a semicolon:

return;
"something";

Example with a Valid Token (Behavior):

The example provided in the question (_a b;) does not result in a semicolon insertion because the identifier _a is a valid token, even though it is missing a semicolon. However, if the line break is removed (_a b;), ASI inserts a semicolon, resulting in a valid statement.

Conclusion:

ASI is a useful feature in JavaScript that allows for more concise code. However, it is crucial to understand the specific rules to avoid syntax errors and unexpected behavior. By following these rules, developers can write clear and reliable JavaScript code.

The above is the detailed content of How Does JavaScript's Automatic Semicolon Insertion (ASI) Work and When Does it Insert Semicolons?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn