DEV Community

Cover image for Are Semicolons Optional in JavaScript ?
Dhairya Shah
Dhairya Shah

Posted on • Updated on • Originally published at snowbit-blog.vercel.app

Are Semicolons Optional in JavaScript ?

JavaScript is a very famous language and has a huge community. Everyone writes code differently but in a similar manner. Today, in this article I am going to talk about Semicolons in JavaScript.

Have fasten the seat-belt and let's go 🚀


JavaScript is having a huge community that divides the Semicolon, some prefer to use it and some do not; even I personally try to avoid using semicolons, which looks better and cleaner.

And this is all possible because of JavaScript which does not have a strict rule to use a semicolon at the end of the line.

This process is known as Automatic Semicolon Insertion

Meme

Some Rules for Automatic Semicolon Insertion

The JavaScript parser will automatically add a semicolon when:

  • Every next line starts with code that breaks the current one
  • when the next line starts with a }, closing the current block
  • when the end of the source code file is reached
  • when there is a return statement
  • when there is a break statement
  • when there is a throw statement
  • when there is a continue statement

So this was it for this article and make sure to comment down what do you prefer to use semicolons or not?

Top comments (3)

Collapse
 
bamartindev profile image
Brett Martin • Edited

In general I prefer when a language doesn't have semicolons (or really any character(s) to signify end of statement) such as Python and Haskell.

That being said, I use semicolons when I am writing JS just because it bothers me if there are sporadic uses of using semicolons when it is necessary while most lines are clean 😉

In my most recent project, I was trying to write without semicolons and ran into an issue I had not encountered before with code like:

const lib = require('some-lib')

(async () => {
  // doing some neat things here in a IIFE
})()
Enter fullscreen mode Exit fullscreen mode

where I got this error:

index.js
(async () => {
^

TypeError: require(...) is not a function
Enter fullscreen mode Exit fullscreen mode

The need for an explicit semicolon can appear at any time!

Collapse
 
volker_schukai profile image
Volker Schukai

Interested developer can find the standard here:
ecma-international.org/12.0/#sec-a...

Collapse
 
bamartindev profile image
Brett Martin

Exactly! I had a brief moment where I considered just doing that, but since I was so early in the project I just decided to add semicolons 🤷‍♂️