There are lots of questions about "should I use semicolons?" and "how does semicolon injection work?", but I wanted to find FUD-free advice for a coder who has decided he want to avoid using semicolons as much as possible.
If someone has, like izs or the Bootstrap devs, chosen to write Javascript without semicolons, under what conditions must they add a semicolon, and what else should they do to ensure their code will not fail?
Assuming you intend to use a newline in place of semicolons, a commonly overlooked mistake is code that combines two lines into a single expression.
For example, the following code:
// DANGEROUS
a = b + c
(d + e).print()
will be interpreted as:
a = b + c(d + e).print()
The solution is:
// SAFE
a = b + c
;(d + e).print()
A similar concern arises with:
// DANGEROUS
console.log()
['three', 'two', 'one'].forEach(console.log)
So in general, the recommended rule to follow is:
When a line starts with a parenthesis
(
or[
or with an arithmetic operator
+
-
*
/
or regexp/.../
then put a semicolon
;
in front of it.
(Note however that ++
--
and //
are safe without a semicolon.)
(You would never actually write *
or /
alone, so it wouldn't make sense to start a line that way, but you might sometimes want to start a line with a /.../
regexp. In that case, if a semicolon is not used, this will most likely cause a syntax parsing error. The (
[
+
-
cases are more dangerous, because they would cause a runtime bug.)
Sources:
For similar reasons, semicolons are also advisable at the start and end of a library script which will be released into the wild. In fact this is recommended regardless of what style you use in your script.
In this example with an IIFE:
// my-library.js
;(function(){
...
})();
The leading semicolon will ensure that your outer parentheses (...)
will not try to invoke an un-terminated expression at the tail end of the script which has been concatenated before yours.
The trailing semicolon is good practice in case the script concatenated after yours starts with an IIFE and neglected to lead with its own semicolon.
As an alternative, Bootstrap leads with a +
, does not wrap the IIFE in (...)
, and ends with a ;
. Other variations lead with !
instead of +
or ;
.
The only other time semicolons are required are in traditional for loops:
for (var i = 0; i < 10; i++) { // good luck doing that without semicolons!
and when you are otherwise placing multiple statements on one line:
x = obj[k]; delete obj[k]; return asChar(x)
Some linters will detect when your code may have unintended consequences, and encourage you to follow the practices above.
For example, the so-called standardjs linter will detect the concerns raised above. (They also have released an eslint config if you prefer to use eslint, but I'm not sure how comprehensive those rules are.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With