JavaScript Semicolon: Do You Really Need It? [2022 Guide]

In JavaScript, semicolons are optional.

Yes, you heard it right.

// Both statements work the same way
console.log("Hello")
console.log("Hello");

However, there are some situations in which omitting a semicolon can lead to unwanted consequences.

So there is no definitive answer as to whether you should use a semicolon or not.

Using semicolons always causes a debate in the JavaScript community. There are good arguments that support using semicolons. But there are also great reasons why you should not use them.

This is a comprehensive guide on how to use semicolons in JavaScript.

First, we are going to walk through the rules of using the semicolons in JavaScript code.

Then you are going to learn how the automatic semicolon insertion works behind the scenes.

Last but not least, you are going to see a list of pros and cons of using semicolons.

At the end of this guide, you should be able to decide if you want to use semicolons or not.

Guide to Using Semicolons in JavaScript

Before discussing the pros and cons of using semicolons, you need to understand how how they are used in the first place.

Required Usage: Separate Two Statements on the Same Line

If you have two JavaScript statements on the same line, you have to separate them by semicolons.

Perhaps the most common example of this is the for loop.

For example:

const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]);
}

Output:

1
2
3
4
5

The for loop would not work without the semicolons when the looping condition is set up on one line.

Optional Usage: Semicolons as Statement Separators

Other than separating statements on the same line, there is no other obligatory usage of the semicolon in JavaScript.

However, you can optionally use the semicolon to terminate a statement even though there were line breaks.

Here are some common examples of statements that can be terminated by a semicolon:

let i;                        // variable declaration
i = 5;                        // value assignment
let x = 9;                    // declaration and assignment
var fun = function() {...};   // function definition
alert("hi");                  // function call

Remember, all the above semicolons are optional.

The code would work without them as well.

Avoid Semicolons

There are also some situations in which you have to avoid using the semicolons.

Avoid Semicolons After ‘}’

Do not put a semicolon after a closing curly bracket ‘}‘.

The only exception is an assignment statement like this:

var data = {name: "Alice", age: 25};

In this case you can use a semicolon.

Here are some examples of not using a semicolon after the closing curly bracket:

if  (...) {...} else {...}
for (...) {...}
while (...) {...}
function (arg) { /* actions */ }

Avoid Semicolons After ‘)’ in an if, for, while, or switch Statement

In the previous section you learned not to use semicolons after the closing curly bracket.

However, if you accidentally do, it is only going to be ignored.

No damage done.

But if you place a semicolon where it is not supposed to be, you are going to run into trouble.

Do not add a semicolon after the closing parenthesis ‘)’ in:

  • If statements
  • For loops
  • While loops
  • Switch statements

Let’s see an example of why this is important to remember.

If you write an if statement like this:

if (0 > 1); { console.log("Hello") }

It is equivalent to this:

if (0 < 1);

console.log("Hello")

In this case, it prints the message to the console even though it clearly should not.

The reason why this happens is because the semicolon terminates the if statement altogether.

Then the code block following the if statement is executed as an individual block of code.

So be careful not to misuse the semicolon!

Exceptions in Using the Semicolon

Earlier in this article, you saw an example of a for loop with semicolons.

This is an exceptional use case of the semicolon.

Take a look at this simple for loop:

for (let i = 0; i < 10 ; i++) { } // Works

As you can see, there is no semicolon right after i++.

As a matter of fact, you cannot use a semicolon after the third statement in the for loop.

If you do, there is going to be a syntax error:

for (let i = 0; i < 10 ; i++;) { } // SyntaxError

This is everything you need to know when it comes to the rules of using semicolons in JavaScript.

Next, let’s briefly discuss why using semicolons is optional in JavaScript.

Automatic Semicolon Insertion in JavaScript

JavaScript does not require semicolons (other than the one exception you saw earlier).

This is because JavaScript is clever and it can add the semicolons where needed automatically.

This happens behind the scenes and you will not notice it.

This process is called Automatic Semicolon Insertion (ASI).

ASI Rules in JavaScript

The JavaScript parser adds a semicolon in any of the following cases:

  1. Next code line starts with code that clearly discontinues the current line of code.
  2. When the next line of code starts with ‘}‘.
  3. When the end of the file is reached.
  4. If any of the following statements are encountered on its own line
    • return
    • break
    • throw
    • continue

It is important to understand that the ASI is not correct 100% of the time.

The semicolon is used to separate statements in JavaScript—not to terminate them.

This is what the ASI tries to do for you.

A plain English way to summarize the ASI rules is:

Not every line break needs a semicolon. Instead, a linebreak that cannot be parsed without a semicolon requires a semicolon.

For example:

let x
x
=
10
console.log(x)

This piece of code is interpreted by the ASI as:

let x;
x = 10;
console.log(x);

In this case, the ASI did a great job of understanding how the code continues between lines 2-4.

However, sometimes it might not know what we are trying to accomplish.

For example, this line of code causes an error

const s = 'World'
const ab = "Hello" + s

[3].forEach(n => console.log(n))

This results in the following error:

Uncaught TypeError: s[3].forEach is not a function
    at <anonymous>:4:5

Based on the error, you may already guess as to why this is happening.

The reason why this valid piece of code does not work is because the ASI does not insert a semicolon after the second line.

Instead, it interprets the lines 2 and 4 as a continuation of the same statement like this (according to the ASI rule number 1):

const s = 'World';
const ab = "Hello" + s[3].forEach(n => console.log(n));

The ASI thinks that s is an array and you are trying to access its 4th element with s[3].

But that is not what you are trying to do.

To make this line work as expected, you should manually add an explicit semicolon at the end of the second line:

const s = 'World'
const ab = "Hello" + s;

[3].forEach(n => console.log(n)) // Prints '3'

Now the code works as expected.

Another example where the ASI might cause issues is with return statements.

For example:

function getData() {
  return
  {
    name: 'Bob'
  }
}

console.log(getData())

Output:

undefined

This prints undefined even though you expected it to print the { name: ‘Bob’ }.

This happens because the 4th rule of ASI states that if a return statement is encountered on its own line, a semicolon is inserted.

So the ASI sees the above code like this:

function getData() {
  return;
  {
    name: 'Bob'
  }
}

console.log(getData())

In other words, the getData() function returns nothing and then randomly creates an object with which it does nothing.

Thus you see undefined in the console.

To fix this, you should add the opening curly bracket to the same line as the return statement:

function getData() {
  return {
    name: 'Bob'
  }
}

console.log(getData())

Output:

{
  name: "Bob"
}

Now this piece of code works as expected.

In this chapter you learned to be careful with the ASI. Even though most of the time it is right, sometimes it can misinterpret your intentions.

Next, let’s get to the interesting part, that is, to the reasons why you should or should not use semicolons in JavaScript.

Why You Should Use a Semicolon: 5 Reasons

Using or not using semicolons causes a heated debate among web developers.

Here are 5 reasons you should use a semicolon in your code.

1. Sometimes Mandatory

As you learned earlier in this article, you sometimes have to use a semicolon.

For instance, if you write a for loop, you have to use semicolons in specifying the looping parameter and the conditions.

Otherwise the loop will not work.

Also, the ASI (Automatic Semicolon Insertion) of JavaScript is not right 100% of the time.

Sometimes it can misinterpret your intentions and not add a semicolon where it should. This can lead to unexpected errors in code.

You also saw one example of this earlier in this guide.

2. You Have Grown to Use Semicolons

Perhaps you have gotten used to using semicolons in your code over time.

Some other languages use semicolons extensively, so it is common to get used to using those.

If your brain does not interpret JavaScript code without semicolons, why drop them?

Feel free to use the semicolons to make the code understandable to you if this is something you have used to do.

3. Be Explicit about Terminating a Statement

Semicolons are an easy way to be really explicit about ending a statement.

Using a semicolon there is no room for confusion.

The line of code terminates at the semicolon.

4. Less to Worry About

If you always use a semicolon, you do not need to worry about the ASI that much.

This gives you less to worry about.

After each line of code you do not have to worry about whether the lack of semicolon messes things up or not.

However, the ASI can still mess things up as you saw in the example of the return statement.

5. The ASI Could Change

The ASI rules could change in the future.

Although it is unlikely, this could still happen.

Thus, relying on the ASI rules of inserting semicolons the same way is not 100% reliable.

If you write code with the current ASI in mind, you could run in some issues if the rules changed.

But keep in mind 99.9% of the time the ASI does its job correctly. Furthermore, the rules are not likely changing anywhere soon.

Now that you have seen a bunch of reasons to use semicolons, let’s talk about why you should not use them.

Why You Should Not Use Semicolons: 3 Reasons

Notice that if you hear someone saying “You should never use semicolons”, they are wrong. This is because the semicolon is mandatory on rare occasions.

Anyway, let’s talk about the cons of semicolons by listing 3 reasons why you should not use them.

1. Semicolons Are Automatically Inserted

As you learned, semicolons are inserted by the ASI.

Thus you do not need to write something that is going to be ignored anyways.

2. Less Code to Write and Less Noise

Each character of code impacts the readability and the quality of code.

If you skip using semicolons, you save characters for each line of code you write.

3. Multiple Statements on One Line Is Bad Practice

Using semicolons allows you to write multiple statements on the same line.

But this is bad practice.

You should never write statements on the same line (unless required).

If you use semicolons, there is a chance you get this bad habit. If you do not use semicolons, there is no way for you to write statements on the same line.

So Should I Use Semicolons or Not?

In the previous chapter we discussed reasons why you should and why you should not use semicolons.

As you can see, there are more good reasons to keep using semicolons than leaving them out.

Thus, I recommend using semicolons.

However, the decision is up to you.

If you are working in a software development team, you have to abide by the common rules. If the team uses semicolons, you have to use them too. If the team does not, you should not either.

Also, remember to be consistent with or without the semicolons.

If you leave one semicolon out, leave out all of them (except for the mandatory ones). You can also configure your linter to automatically remove semicolons.

Conclusion

Today you learned about using semicolons in JavaScript.

To recap, semicolons are not mandatory in JavaScript.

Instead, the Automatic Semicolon Insertion (ASI) process adds semicolons where necessary.

However the ASI is not correct 100% of the time. Also, in some situations, you simply have to use a semicolon. Otherwise the code will not work.

Whether you should use semicolons or not is completely up to you.

In my opinion, there are more benefits of using semicolons than leaving them out.

But your mileage may vary.

Thanks for reading.

Hope you find it useful.

Happy coding!

Further Reading

103 JavaScript Interview Questions