Home >Web Front-end >JS Tutorial >How Does JavaScript's Automatic Semicolon Insertion (ASI) Work and How Can I Avoid Its Pitfalls?

How Does JavaScript's Automatic Semicolon Insertion (ASI) Work and How Can I Avoid Its Pitfalls?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 05:42:15749browse

How Does JavaScript's Automatic Semicolon Insertion (ASI) Work and How Can I Avoid Its Pitfalls?

JavaScript's Automatic Semicolon Insertion (ASI) Rules

JavaScript's ASI is a feature that can automatically insert semicolons at the end of certain statements if they are missing. This can be useful in some cases, but it can also lead to bugs.

Statements Affected by ASI

ASI is applied to the following types of statements:

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

ASI Rules

The specific rules for ASI are as follows:

  1. If an invalid token is encountered that is not allowed by the grammar, a semicolon is inserted before it if:

    • The token is separated from the previous token by at least one line break.
    • The token is a closing curly brace (}).
  2. When the end of the input stream of tokens is encountered and the parser cannot parse the input token stream as a single complete program, a semicolon is automatically inserted at the end of the input stream.
  3. If a token is allowed by the grammar, but the production is a restricted production, a semicolon is automatically inserted before the restricted token.

Restricted productions include:

  • Update expressions ( , --)
  • Continue statements
  • Break statements
  • Return statements
  • Throw statements
  • Arrow functions
  • Yield expressions

Examples

Example 1:

{ 1
2 } 3

ASI will transform this code to:

{ 1
;2 ;} 3;

Example 2:

a = b
++c

ASI will transform this code to:

a = b;
++c;

Example 3:

return
"something";

ASI will transform this code to:

return;
"something";

Avoiding ASI Bugs

ASI can be a useful feature, but it can also lead to bugs. To avoid ASI bugs, it is best to always use semicolons explicitly at the end of each statement.

The above is the detailed content of How Does JavaScript's Automatic Semicolon Insertion (ASI) Work and How Can I Avoid Its Pitfalls?. 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