24 May 2022 - Ronald
When are Javascript semicolons (;) optional? And when are they mandatory (or recommended at least)? Let’s find out.
I personally use semicolons at the end of every statement, except the ones ending with curly brackets, like function declarations for example. Other developers hate them and avoid them whenever possible. So when are they optional and when are they mandatory?
Most Javascript statements and declarations must be terminated with a semicolon, but that doesn’t mean you have to explicitly write them in your source code. The fact that such semicolons may be omitted from the source in certain situations is due to Javascript doing what’s called Automatic Semicolon Insertion.
There’s certain rules for when this automatic insertion is done. If you want to check them you can read ECMAScript’s Automatic Semicolon Insertion specification.
The rules are complex, but you can generally assume that JavaScript inserts a semicolon after a line break if the next nonspace character cannot be interpreted as a continuation of the current statement.
Let’s consider the following code:
let a
a = 1
console.log(a)Let’s analyse the first line break. Javascript couldn’t interpret
let a a = 1It throws “Uncaught SyntaxError: Unexpected identifier”. So a semicolon is inserted, as if it was written as follows:
let a
;a = 1Which is valid. The second line break is similar:
a = 1 console.log(a)It throws the same error “Uncaught SyntaxError: Unexpected identifier.” So again a semicolon is inserted, as if it was written as follows:
a = 1
;console.log(a)So far we have seen when you can safely omit semicolons, because Javascript does automatic semicolon insertion. But when do you have to write them?
If a statement begins with (, [, /, +, or -, there is a chance that it could be interpreted as a continuation of the statement before.
For example:
a = b + c
(d + e).print()is not transformed by automatic semicolon insertion, because the parenthesized expression that begins the second line can be interpreted as an argument list for a function call:
a = b + c(d + e).print()In this case it’s a good idea for the programmer to provide an explicit semicolon at the end of the preceding statement:
a = b + c;
(d + e).print()This is the reason some libraries have code that begins with a semicolon, like this:
/**
* Library XYZ
*/
;(function () {
// some code here
}It’s just a guard in case this code gets appended to code not properly ended with a semicolon.
Find frontend remote jobs and others at RemoteGecko.com