DEV Community

adriennemiller
adriennemiller

Posted on • Edited on

Semicolons in JavaScript: To Use or Not to Use?

During one of our first JavaScript lectures at the Flatiron School, the instructor mentioned that semicolons are optional in JavaScript… except when they’re not 🤔

I decided to look more into semicolon usage in JavaScript to truly understand why we would or would not want to use them, and use this knowledge to avoid creating any bad habits early on.

Peter Arkle semicolon drawing
Peter Arkle, https://opinionator.blogs.nytimes.com/2012/07/02/semicolons-a-love-story/

Automatic Semicolon Insertion (ASI)

The reason semicolons are sometimes optional in JavaScript is because of automatic semicolon insertion, or ASI. ASI doesn’t mean that actual semicolons are inserted into your code, it’s more of a set of rules used by JavaScript that will determine whether or not a semicolon will be interpreted in certain spots. I found a helpful lecture from Fullstack Academy on the topic, which you can check out here. I also found a blog post from Bradley Braithwaite on the topic. Below I highlight the main takeaways from these resources.

3 Automatic Semicolon Insertion Rules:

Here are 3 main points to be aware of when it comes to ASI.

1- A semicolon will be inserted when it comes across a line terminator or a '}' that is not grammatically correct. So, if parsing a new line of code right after the previous line of code still results in valid JavaScript, ASI will not be triggered.

Example 1:



var beef 
var cheese 


Enter fullscreen mode Exit fullscreen mode

will become:



var beef; 
var cheese; 



Enter fullscreen mode Exit fullscreen mode

Example 2:



var a 
    b= 
    3;


Enter fullscreen mode Exit fullscreen mode

here, grammar doesn't expect to see b after a, so ASI is triggered



var a; 
b = 3;


Enter fullscreen mode Exit fullscreen mode

Example 3:



a = b + c 
(d + e).print() 



Enter fullscreen mode Exit fullscreen mode

equals:



a = b + c(d + e).print();



Enter fullscreen mode Exit fullscreen mode

2- If the program gets to the end of the input and there were no errors, but it's not a complete program, a semicolon will be added to the end. Which basically means a semicolon will be added at the end of the file if it's missing one.

3- There are certain places in the grammar where, if a line break appears, it terminates the statement unconditionally and it will add a semicolon. One example of this is return statements.




function getCheese() {
    return 
    { 
       cheeseType: "Gouda"
    } 
}


Enter fullscreen mode Exit fullscreen mode

This would trigger ASI and result in:




function getCheese() {
    return; 
    { 
       cheeseType: "Gouda"
    } 
  }


Enter fullscreen mode Exit fullscreen mode

Expressions in a return statement should begin on same line, like this:



function getCheese() {
return {
cheeseType: "Gouda"
}
}

Enter fullscreen mode Exit fullscreen mode




When Should I Not Use Semicolons?

Here are a few cases where you don't need semicolons:

if (...) {...} else {...}
for (...) {...}
while (...) {...}

Note: You do need one after: do{...} while (...);

Final Thoughts

If you're going to write your JavaScript without optional semicolons, it's probably good to at least know what ASI is doing. For example, compression or minification could cause your valid code to throw an error because those programs may rely on semicolons.

Also, it can be harder to debug without semicolons since your code may be concatenating together without you realizing it. If you put a line break where there shouldn't be one, ASI may jump in and assume a semicolon even if there shouldn't be one.

keep calm it's only a semi colon
https://www.everywordcounts.co.uk/no-need-to-be-scared-of-semicolons/

Companies and open source projects will likely have a preference one way or another, so be sure to note what it is.

Finally, if you think you may be running into errors due to ASI, check out Babeljs.io to debug - it allows you to put in your code and shows you where ASI semicolons are being inserted.

What have you found to be true when it comes to semicolons in JavaScript?

Latest comments (23)

Collapse
 
renato76 profile image
Renato Mignogna • Edited

Interesting that most people like using semicolons. Personally I do not like using them at all, I actually find them a little bit annoying haha!

I can clearly see the end of each line or statement, my linter makes me break long lines into multi lines that area easily readable, so I can't really see the point of adding these little annoying things at the end of each line, it certainly does not make code more readable for me. It's a matter of opinin I guess, and also what each individual is more used to.

dev-to-uploads.s3.amazonaws.com/up...

Collapse
 
sreramk profile image
Sreram K • Edited

I am a beginner to JavaScript, but from reading this I think it will be unacceptable to not use semicolon whenever possible!

It makes sense to omit semicolon in a language like python as every line break functions as a statement terminator. But if the statement termination is being inferred from the grammar rules, this is where you must ask: why is this even allowed in the first place?

Collapse
 
eterychan profile image
Eternia • Edited

Your reason is one which makes sense the most; by comparing it with Python. I can live without semicolons if the language I am using disregard them to begin with. But if the language actually needs them and the interpreter adds them for me by following three simple rules; I would rather add them myself!

Collapse
 
fchaplin profile image
Frederic CHAPLIN • Edited

I tried a project without semicolon. 
It's a full-stack project, with typescript/node/express on backend and React/JavaScript on frontend. 

Here are my conclusions on it :

  • I encountered no compiling error so far. 
  • I had no readability issues. My code felt cleaner and more readable to me without the "semicolon noise".
  • But the next developer on the project may find this disturbing

I will use the semicolon again, and stick to the good practices for now. Mainly because I'm afraid of the dreaded compiling bug that may occur and because I care for others.

But I clearly think that JavaScript is much better without semicolons.

Collapse
 
vuongtran21 profile image
vuongtran

My thinking is still using semicolons for convention and readable code. I'm writing application using Vuetify, and default eslint setting without semicolons. That make me feel not comfortable with it.

Collapse
 
fasani profile image
Michael Fasani

I just wanted to say: google.github.io/styleguide/javasc...

Relying on implicit insertion can cause subtle, hard to debug problems. Don't do it. You're better than that.

Omitting them is simply a bad practice whatever your reasons.

Collapse
 
zimaben profile image
Benny T

I don't find semicolons any more readable than their absence...but when I skip them I generate a lot more errors when I'm coding in other languages.

I don't mind the extra keystroke as much as I do clearing like 8 500 errors on a page because i zoned into no-semis mode.

Collapse
 
kenyo profile image
Ken Yo

Good reading!

Collapse
 
outlawgametools profile image
J. A. Whye

I know this is an older article, but I didn't want someone coming here, reading all the comments and thinking, "Oh, everybody uses semicolons, I guess I'd better..."

Not everybody does. Why type something you don't need to?

I program in C# for my job so am required to use semicolons at the end of the lines. But at home when I'm working on something in Lua, or Javascript, I skip the semicolons. They are generally NOT needed so I don't include them.

If your boss says you have to use them, then use them, but otherwise, why bother?

Collapse
 
rapmendoza profile image
Rap Mendoza

Hey man, I understand your point - but doesn't it help if you have something less to think about, such as these rules, and focus on the things that actually matters? I mean you can predict better at what would happen in your code without thinking about such rules.

Collapse
 
dlopez831 profile image
David Lopez (Argen.)

yes... Why bother writing comments if the compiler / interpreter ignores them?

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

Personally, I write all of my code with semicolons. and also "", so that I can use IIFE, especially async IIFE.

Double quotes, so that I don't forget when I program in other programming languages.

Also, double space, rather than Tab.

Never have been in a corporate env where everything is forced, though.

Collapse
 
balachalasani profile image
Bala Chalasani

There is a typo in point 1 example 2 in the ASI interpreted code:

Should be

var a;
b = 5;

Instead of:

var a;
b = 3;

Collapse
 
adriennemiller profile image
adriennemiller

Thanks, updated!