JS Interview #3 — Automatic Semicolon Insertion (ASI)

Mighty Ghost Hack
Mighty ghost hack
Published in
2 min readJan 7, 2023
Automatic Semicolon Insertion

Let’s talk about Semicolon, if you work with multiple programming languages semicolon are mainly preferred to end the statement, which helps the interpreter to understand the code.

Now when you work with javascript you might wonder why javascript does not restrict developers to permanently end the statement with a semicolon.

That is possible only because of Automatic Semicolon Insertion (ASI).

Automatic Semicolon Insertion

ASI means, it will insert a semicolon if it's not added explicitly.

Here for the convenience of the programmer (less typing, stylistic preference, less code noise, lower barrier to entry), semicolons may be omitted in some source text locations, with the runtime automatically inserting semicolons according to a set of rules set out in the spec.

Rules of Automatic Semicolon Insertion

  1. when the next line starts with code that breaks the current one.
  2. when the next line starts with a }, closing the current block.
  3. when the end of the source code file is reached.
  4. when there is a return statement on its line.
  5. when there is a break statement on its line.
  6. when there is a throw statement on its line.
  7. when there is a continue statement on its line.

Ex, Automatic Semicolon Insertion does not work properly

Example 1 — When return statement on its own line.

let test = function hoisted() {
return
{
a: 'Hello World'
}
};

const output = test();
console.log(output);

You’ll get the undefined as an output

Example 2 — When a semicolon is missing and the javascript interpreter considers it as a continue statement.

const hey = 'hey'
const you = 'hey'
const heyYou = hey + ' ' + you

['h', 'e', 'y'].forEach((letter) => console.log(letter))

Here You’ll get the cannot read properties of undefined (reading ‘forEach’)

Key Points to remember

  • Pay attention and use semicolons. it's a good practice to have a semicolon at the end.
  • If you did not put a semicolon at the end, then make sure the line should not end in with improper way.
  • “use strict” statement or strict mode will not give any error if you not entering the semicolon.

To understand in a much better way here is the video link

--

--

Mighty Ghost Hack
Mighty ghost hack

A passionate full-stack developer, Ethical Hacker, Blogger, Youtuber and many more