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

How Does JavaScript's Automatic Semicolon Insertion (ASI) Work and When Does It Occur?

Barbara Streisand
Release: 2024-12-21 19:52:13
Original
870 people have browsed it

How Does JavaScript's Automatic Semicolon Insertion (ASI) Work and When Does It Occur?

Automatic Semicolon Insertion in JavaScript: Detailed Rules

JavaScript's automatic semicolon insertion (ASI) is a controversial feature that can insert semicolons at certain points in code where they are not explicitly written. Understanding ASI's rules is crucial to avoid potential bugs and ensure proper code execution.

ASI-Affected Statements

ASI only applies to specific types of statements:

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

ASI Rules

ECMAScript §11.9.1 outlines three cases where ASI can occur:

Case 1: Offending Token

If an invalid token is encountered and it follows a LineTerminator, a semicolon is inserted before it, except for '}'.

Case 2: End of Input Stream

If the parser cannot complete the program, a semicolon is inserted at the end of the input stream.

Case 3: Restricted Production

A semicolon is inserted before restricted tokens, which include:

  • Update expressions without LineTerminators after operands (e.g., c)
  • Continue and break statements without labels or semicolons
  • Return statements without expressions
  • Throw statements without expressions
  • Arrow functions without parentheses after parameters
  • Yield expressions without parentheses after * or yield

Example of ASI in Practice

Consider the following code:

return
"something";
Copy after login

According to Case 3, ASI inserts a semicolon before the restricted production return statement, resulting in:

return;
"something";
Copy after login

Conclusion

ASI can be a tricky feature to handle, but understanding its rules is essential for writing robust JavaScript code. By adhering to these rules, developers can avoid errors and ensure the correct execution of their programs.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template