Why JavaScript Semicolons?

Semicolons: Are they Required Or Not?

Do a quick google search on whether or not semicolons are required when writing JavaScript. You’re going to hear all sorts of noise about automatic insertion and how this is sufficient. Let me warn you, there are specific instances where you must use semicolons, and I will give a couple of examples below. And before you start to say the opposite read the following from the EcmaScript Standards: “Certain ECMAScript statements must be terminated with a semicolon… For Convenience, however, such semicolons may be omitted from the source text in certain situations… These situations are described by saying that semicolons are automatically inserted…”

Are They Ever Optional?

Are they ever optional? In many situations yes, but my question to you is this best practice? I am going to affirm that no, you should use semicolons in the areas that makes the most, even if they are automatically inserted by ECMAScript standards.

Three Rules For Semicolons

These rules are taken directly from the ECMAScript Standards. So these rules are the standard behavior and that is what we ought to base any assumptions about our code on.

Rule One Broken Down

This rule tends to be the most verbose, but in my opinion is probably the easiest to understand when written as code, so I’ll lay out the rule and then show an example of what it means.

  • “When, as a Script or Module is parsed from left to right, a token is encountered that is not allowed by any production of the grammar.”

  • “The offending token is separated from the previous token by at least one line terminator.”

Both of these circumstances will be followed by an automatically inserted semicolon if one is not present. In other words, as our code is being read by the compiler, it is looking for line terminators, or tokens that don’t make sense being placed next to one another. In the below, the var a = 1 is going to be the most logical piece of code and will be separated from var b = 2

var a = 1 var b = 2

This becomes

var a = 1; 
 var b = 2;
  • The next part of rule one is that where there is an offending curly brace or }, there will be an automatic insertion. Below automatic insertion of a semicolon will look like is this:

if(true){console.log("I'm true")} Will have a semicolon inserted before the closing curly brace. if(true){console.log("I'm true";)}

Hopefully that all makes a bit more sense. 🙂

Rule Two Broken Down

“When, as the Script or Module is parsed from left to right, the end of the input stream of tokens is encountered , then a semicolon is automatically inserted at the end of the input stream“. ~ EcmaScript Standards

This one as well is fairly straightforward and I will show with an easy to follow example below.

console.log("place a semicolon at the end of me")

becomes:

console.log("place a semicolon at the end of me");

So Why All The Fuss If They Are Inserted Automagically?

Notice the bracket in our array of sandwich items below. :hamburger:

There is going to be a runtime error when attempting to parse this code by the compiler as the [ is an allowed token. Remember from our state rule that “When, as a Script or Module is parsed from left to right, a token is encountered that is not allowed by any production of the grammar” a semicolon is inserted. So if the token is allowed then no semicolon will be inserted.

var one = 1
  var two = 2
  var three = one + two   //no semicolon...

['bread', 'pickles', 'turkey', 'cheese'] //runtime error here
   .forEach(function(item){
      console.log(item)
})

Another example is when using an IIFE, if you don’t know what an IIFE is, I’ve written about them here.

var one = 1
var two = 2
var three = one + two //no semicolon inserted
    
(function(){ //runtime error here
    console.log("Immediately Invoked Function Expression or IIFE")
}())

Things can break when this occurs even if infrequently, so be mindful. I will give a couple of suggestions below.

Rule Three Broken Down

“When, a token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token of a restricted production, and the restricted token is separated from the previous token by at least one line terminator, then a semicolon is automatically inserted before the restricted token.”

What is meant by Restricted Production?

Take a look at the below JavaScript keywords. These signify the end of a statement and without a semicolon, you will end up with a mayhem I tell you, or maybe in the example I am going to give you, you’ll just get undefined.

  • continue
  • break
  • throw
  • return

Note that when called this function is going to return undefined, which is going to be unexpected behavior, as return will automatically insert a semicolon after it if one is not present after our object!

function returnAnObject(){
     return //a semicolon will be inserted here automatically! 
      {
         anObject: "object" // this object is not going to be returned... 
      }
    }
 

So what is the fix?

My recommendation for any developer, experienced or noob, is to use a good linter (JShint or ESlint) and a good IDE/Editor that will warn you of such issues. In my opinion, and most other experienced developers will confirm that this is the best practice for writing clean, maintainable code which functions and behaves as expected.

Next On FoC

A Computer Science Degree to Write Code

A Computer Science Degree to Write Code
Previously On FoC

Finding Your Niche as a Developer

Finding Your Niche as a Developer