Going semi-colon-less. OR why I’m considering the NPM Style Guide.
So, let’s just not rely on stupid ASI and always write semi-colons. It sounds good enough. It sounds logical. Also, Douglas Crockford said it, so it’s probably the right thing to do.
But, the more time I spend writing semi-colons, the more I realize that you can’t really avoid the ASI by putting semi-colons. I agree that the JS ASI is weird and strange. But it is not inconsistent. It has a certain set of rules that work in every browser.
To use a saying made famous by Nokia, using semi-colons to avoid the ASI is like pissing in your pants to keep yourself warm. You see using semi-colons makes you forget about the ASI. You start assuming that your code will just work because you are putting semi-colons. But this is where we all go wrong.
The ASI surprises in two ways:
- It doesn’t put a semi-colon when you expect it to.
In all the research I have done, this only happens when a line begins with an open paren, or bracket:
var a = b .length // becomes: // var a = b.length; var a = b (new Date()).valueOf() //becomes // var a = b(new Date()).valueOf();
You see if the ASI can make sense of your code without putting a semi-colon it will do that. This is exactly why everyone puts semi-colons everywhere. For these two edge-cases. Really.
But here’s the flip side. Here is an example of when the ASI puts a semi-colon when you don’t expect it to:
return someValue - 2 // becomes // return; // someValue - 2;
Well in the first case, if we put semi-colons everywhere, our problem would be solved. But about this case?
return someValue - 2;
You know what gets returned? NOTHING. Yes. putting semi-colons manually everywhere doesn’t save you from the ASI putting in more semi-colons, when you don’t want them.
And if we do have to understand how the ASI works we might as well save ourselves some typing by not putting semi-colons when we don’t need them.
Further, and this is why I like the NPM style guide, if we don’t write semi-colons when we don’t need them, we can write more readable code that helps new developers really understand the ASI.
Take this for example:
// Works but doesn't teach you anything about the ASI. var a = b; .length; var a = b; (new Date()).valueOf(); // Works, but also teaches you about the ASI var a = b ;.length var a = b ;(new Date()).valueOf()
By using semi-colons before open parens and brackets, we write code that will teach new developers the nuances of the ASI. It will force them to understand the ASI, and protect themselves from unfortunate surprises. If we keep writing semi-colons everywhere, we are more likely to forget that the ASI even exists and run into surprises.