No, you don’t need semicolons
/me beats dead horse
I recently came across this book which makes an argument that since ASI is an error-correction tool, writing your programs without semicolons means your programs are incorrect and “errored”.
I completely disagree and do not think developers need to be shamed into adding semicolons to their programs when they aren’t required.
The fact is semicolons are mostly optional because ASI exists and inserts them in for you. You can’t just pretend ASI doesn’t exist.
What are tools for if we are not meant to use them?
“But wait, I add semicolons because then I don’t have to think about it.” the pro-semicolon camp supporters say.
Adding semicolons to your programs does not automatically exclude you from the rules of ASI. For example:
function whoNeedsASI() {
return
{
key: 'value'
}; // This semicolon will not help you.
}
The rules of where to insert the semicolon are not easy to remember, it’s not just at the end of everything. You will need to learn some exceptions. There’s a reason this warning exists.
function foo() {
var a = true; // here is good?
}; // does it go here?function bar() {
return (
1 + 2; // ruh roh.
) // dang, I forgot the semicolon
}var a = foo.filter(function (x) { return x == 2 }); // wait, a semicolon should go in there toovar b = foo.filter(x => x == 2;); // Parser error :(class Foo {
constructor() {
this.bar = 'baz';
}
}; // Maybe?
Adding them just to appease the interpreter so ASI doesn’t have to is a weak argument. Code is for humans to read and write; the machine will not feel better if you include the semicolon.
JS VMs don’t care about you and your semicolons or lack thereof.
If you’re in the habit of omitting semicolons, the rules of where semicolons are required are pretty easy to grok:
1. for loops.
2. if your next line begins with `[`, `(`, or any of the arithmetic operators `+`, `-`, `*`, `/`.
Real reasons for not using semicolons:
- It’s easier to remember when a semicolon is required vs when it is not.
- It is less typing.
This is an aesthetics debate: some people prefer the punctuation when reading, and others don’t. This is entirely reasonable and acceptable.
The moral of this story: ASI is (formally speaking) a syntactic error correction procedure. If you start to code as if it were a universal significant-newline rule, you will get into trouble. .. I wish I had made newlines more significant in JS back in those ten days in May, 1995. .. Be careful not to use ASI as if it gave JS significant newlines.
I think we can all agree not to treat JS as if it has significant newlines, because it doesn’t. But we should strive to understand ASI, because we have to. And finally, we can stop typing that extra character if we feel like it because JavaScript ultimately doesn’t care if we do or don’t.
For more information on understanding ASI see: