Gotchas where automatic semicolon insertion can lead to bugs

I took Effective JavaScript training by Douglas Crockford a few months ago. One thing that stuck with me since then is the importance of using explicit semicolons in JavaScript. For a while, I have been lazily avoiding writing the ; and assuming the parser will do my job correctly for me. In this post, I want to present some examples that changed my mindset.

1*zX_jJO9HQX5r3WQzQe6xNQ

Example 1

What do you expect the output of this to be?

const test = () => {
 return 
 {
  ok : true
 }
}
console.log(test())

You would expect the output of this to be an object with a property ok set to true. But instead, the output is undefined. This is so because since the curly brace starts on a new line, automatic semicolon completion changes the above code to this:

const test = () => {
 return;
 {
  ok : true
 }
}

Fix: Use curly braces on the right of return and explicit semicolons:

const test = () => {
 return {
  ok : true
 }
};

Example 2

const a = 1
const b = 2
(a+b).toString()

What do you think happens in the above code? We get an error Uncaught ReferenceError: b is not defined. This is because the parenthesis on the third line is interpreted as a function argument. This code is converted to this:

const a = 1;
const b = 2(a+b).toString();
In the circumstance that an assignment statement must begin with a left parenthesis, it is a good idea for the programmer to provide an explicit semicolon at the end of the preceding statement rather than to rely on automatic semicolon insertion.

— ECMA-International.org

I have learned to be careful when using automatic semi-colon insertion.

Further Reading —

  1. Automatic semicolon insertion rules
  2. Blog post by Bradley Braithwaite inspired by the same lecture

Did you learn something new? Have comments? Know a DevJoke? Tweet me @shrutikapoor08