All Articles

Automatic Semicolon insertion in JS

When you write code in JS you can omit semicolons (mostly…we’ll come to that later). There is a reason you could do that it is because of Automatic semicolon insertion. When the code you wrote gets parsed because of Automatic semicolon insertion(ASI) your code is treated as if semicolon is inserted in certain place using some set of rules. But like everything it is not perfect and you may end up with some weird edge cases where your code may not behave as expected.

Rules for ASI

Rule number 1

When there is a newline separating two tokens or there is statement before `} then semicolon is inserted. Let’s say you have the following code segment

function sayName(name){
  const name = 'Your name'
  const greetings = `Hello ${name}`
  return greetings
}

then the above code is treated as if as follows

function sayName(name){
  const name = 'Your name';
  const greetings = `Hello ${name}`;
  return greetings;
}

But if you have code as follows ASI can screw it up for you

  let i
  j = 5

then ASI treats it as

  let i;
  j = 5;

creating new global variable j for you

Rule number 2

When the parser reaches the end of the code it inserts semicolon

const name = 'Photography Raptor'
const greetings = sayName(name)

console.log(greetings)

will now become

const name = 'Photography Raptor';
const greetings = sayName(name);

console.log(greetings);

Rule number 3

When you have continue, break, return or a throw statement and it is followed by newline then semicolon is inserted

so if you have code

function getOne(){
  return
    1
}

then it becomes

function getOne(){
  return;
    1;
}

Your code now returns undefined and the next line is unreachable code.

Conclusion

When you transpile your Typescript, ES6 code or minify it sometimes it can result in weird bugs due to above ASI rule that may be hard to debug. Tools prettier by default adds semicolon at the end. But in the end it is a matter of preference and you should be aware of ASI rules if you decide to not insert semicolons.