Home > Web Front-end > JS Tutorial > How Does JavaScript's Automatic Semicolon Insertion (ASI) Work: Rules and Exceptions?

How Does JavaScript's Automatic Semicolon Insertion (ASI) Work: Rules and Exceptions?

DDD
Release: 2024-12-28 04:58:10
Original
440 people have browsed it

How Does JavaScript's Automatic Semicolon Insertion (ASI) Work: Rules and Exceptions?

ASI in JavaScript: Rules and Exceptions

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:

  • Empty statements
  • Variable declarations (var)
  • Expression statements
  • Control flow statements (do-while, continue, break)
  • Return statements
  • Throw statements

ASI Rules

ASI is applied in three main cases:

  1. Invalid Token: When an unexpected token is encountered, a semicolon is inserted before it if:

    • The token is preceded by a line break.
    • The token is the closing curly brace }.
  2. End of Input Stream: If the end of the input stream is reached without a complete Program, a semicolon is inserted at the end.
  3. Restricted Tokens: Semicolons are automatically inserted before tokens that follow restricted productions in the grammar. This includes tokens without line terminators:

    • Update expressions ( , --)
    • Control flow statements (continue, break)
    • Return statements
    • Throw statements
    • Generator function expressions
    • Yield expressions

Example 1 (Invalid Token):

{ 1
2 } 3
Copy after login

ASI transforms this code into:

{ 1
;2 ;} 3;
Copy after login

Example 2 (End of Input Stream):

a = b
++c
Copy after login

ASI adds a semicolon at the end:

a = b;
++c;
Copy after login

Example 3 (Restricted Token):

return
  "something";
Copy after login

ASI inserts a semicolon before the restricted return token:

return;
  "something";
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template