Are Semicolons Required in JavaScript?
Semicolons in JavaScript divide the developers. Some JavaScript developers use semicolons at the end of every statement, and some use them only where strictly required. Many developers fall somewhere in between, and a few even intentionally include extra semicolons as a matter of personal style.
Interestingly, JavaScript does not strictly require semicolons, which is why all these approaches are possible. However, when a semicolon is necessary for the code, JavaScript adds it automatically behind the scenes. This process is called Automatic Semicolon Insertion.
Even if you choose to use semicolons at the end of every statement, certain constructs in JavaScript can have parsing behaviours that are not immediately obvious. Regardless of your personal preferences regarding semicolon usage, it is crucial to understand the rules of Automatic Semicolon Insertion for writing JavaScript.
By familiarizing yourself with a few simple rules, which are explained here, you will gain the ability to comprehend how any program you come across is parsed.
Here are 2 rules that you should remember
-
The expression after one of the keywords
return
,throw
,yield
,break
, andcontinue
must be on the same line as the keyword itself. These keywords often stand alone, but they are sometimes followed by an identifier or expression. If a line break appears after any of these words, JavaScript will always interpret that line break as a semicolon.Example of a return statement not on the same line with expression.
Example of a return statement not on the same line with expression.
Example of a continue statement not on the same line with expression.
-
If a line starts with one of
(
,[
,`
,+
,-
, or/
, end the previous line with a semicolon. If a statement begins with any one of these, there is a chance that it could be interpreted as a continuation of the previous statement.Be mindful of semicolons when lines start with certain characters.
Should you omit optional semicolons or not?
It is ultimately a matter of personal preference. However, this decision should be based on informed choices rather than vague concerns about potential syntactical issues. By understanding the rules outlined here, you will be empowered to make your own choices and read any JavaScript code with ease.
Get my free, weekly JavaScript tutorials
Want to improve your JavaScript fluency?
Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.
Join today, and level up your JavaScript every Sunday!
Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.