Automatic Semicolon Insertion

Javascript sometimes allows us to bypass semicolons when writing scripts and it can easily detect semicolons without any trouble. But the interesting thing is, this behavior formalizes misunderstanding when learning it. The documentation, which describes such type of behavior of the languages is also written in a little bit of hard language.

In this article, I’ll try to summarize and easily explain the fundamentals of Automatic Semicolon Insertion ( “ASI” in short)

PS: Try to add a semicolon manually where it requires to be added. Don’t rely on language’s features.

After “{“ and )” symbols JS will add a semicolon automatically when it will see LineTerminator (enter etc) ahead and for that reason, the below code will work without any issue.

console.log("This is very interesting")
console.log("to learn JS")

Before “[]” JS can’t add semicolons. the below code will fail

console.log("We're trying to execute this code")[1, 3, 4].forEach(element => {
    console.log(element);
});

Before ++ and -- JS will add a semicolon


++ 
y

It is parsed as x; ++y;, not as x++; y

Semicolon will be added automatically at the end of the page.

Below statements are affected (JS will add semicolon)

  • var statement
  • expression statement
  • do-while statement
  • continue statement
  • break statement
  • return statement
  • yield statement
  • throw statement
function calculate(a, b) {
    return
    a + b;
}