The age-old JavaScript question of whether to use semicolons in your code or not is a divisive one. What I’ve discerned from reading numerous blog posts and documentation is that neither option of “always using semicolons” and “never using semicolons” is right. Below I’ll explain why and give some examples to back up my findings.
Always use semicolons
A semicolon is what breaks up statements in your code. They can be omitted though if the statement is followed by a line break. A semicolon is only necessary when you have two or more statements on the same line.
var i = 1; i++ //semicolon is necessary
var i = 1 //semicolon is optional
i++ //semicolon is optional
You shouldn’t put a semicolon after a closing curly bracket }. The only exception is assignment statements, such as var obj = {}; where it is assigning an object or function to a variable and therefore makes it optional.
if (…) {…} else {…} //No semicolon
for(…) {…} //No semicolon
while (…) {…} //No semicolon
function (arg) {…} //No semicolon
It isn’t going to harm your code to use semicolons in the above examples but typically you don’t see it used.
A semicolon after round brackets, (), of an if, for, while, or switch statement is going to cause problems though.
if (0 === 1); { alert(“Hello there”) }
//is the same as
if (0 === 1);
{ alert(“Hello there”) };
The semicolon makes JavaScript think that your if statement is empty and therefore the block with the alert is executed no matter what is happening in the line above it.
Never use semicolons
This method is a bit simpler. There’s only one rule: Never start a line with [, (, or `. In these cases you prepend the line with a ;
;[1, 2, 3].forEach(foo)
This seems a little needless though because it is typically better practice to set that array as a variable before doing anything to it.
const array = [1, 2, 3]
array.forEach(foo)
Conclusion
What it really boils down to is personal preference and what is best for your team/group of people that are going to be using your code. This only works though as long as you know all the rules and don’t get bugs from your choice. Personally, I prefer to never use semicolons (mostly because it looks cleaner). But depending on what my team in my next job uses, I’ll definitely adapt to their style guides.