4 ms·
I used to believe as you do that semicolon issues were contrived and unlikely in JavaScript. But over the years I've been bitten by it enough times to know bett
by mistercow 13y ago
I used to believe as you do that semicolon issues were contrived and unlikely in JavaScript. But over the years I've been bitten by it enough times to know better.
IIFEs are the most common source of semicolon problems:
for(i = 0; i < 10; i++){
x = arr[i]
(function(x) {
setTimeout(function(){console.log(x)})
})()
}
A less common sort of pattern that I still use pretty often as a DRY measure:
init()
[x, y, z].forEach(function(a){
if(a.length > 5) {
process(a)
}
})
This is clean and readable, and without semicolons it's completely wrong.
Now sure, you can prepend semicolons to these specific cases, and that will work. Here's why I dislike that:
1. Those leading semicolons look weird. To the uninitiated, it looks like a typo, and that's a significant hazard if anyone else is going to touch your code.
2. While there are only a handful of special rules like this to remember, there's only one rule to remember if you don't rely on ASI.
- Tloewald 13y agoGood examples actually. (Makes me feel better about my ingrained semicolon habit.) Your examples will crash immediately and at the right spot though. The problems I see caused by excessive use of semicolons are often far weirder. That said, inadvertent errors caused by semicolon insertion are still more common and baffling (especially by people addicted to jslint who use a variable declaration idiom particularly easy to screw up with errant semicolons).
- mistercow 13y agoThe first example won't crash if the rvalue preceding the IIFE is a higher-order function (specifically, one that outputs a function). A relatively rare scenario, but a brutal one to debug. As for errors caused by extra semicolons, they can be weird, but I don't think I've ever actually hit one in practice. They'd also be a little easier to spot, since you tend to develop a reasonable instinct for where semicolons belong.
- Tloewald 13y agoI'd say it's a lot easier to be suspicious of lines of code that start with '(' or '[' than find semicolons at the end of the wrong line. It's incredibly easy to put a semicolon where a comma is expected and vice versa. I do it all the time (usually causing an immediate error so it's not a huge deal).