> weird invisible things that trip you up like hoisting
Huh? How can you get tripped up by hoisting? I'm genuinely curious.
Huh? How can you get tripped up by hoisting? I'm genuinely curious.
for (var i = 0; i < 100; ++i) {
foo().then(function() { bar(i); });
}
Then when they realize why this doesn't work, try something like: for (var i = 0; i < 100; ++i) {
var j = i; // this is inside the block, so it's scoped to it, right?
foo().then(function() { bar(j); });
}
And then that breaks too, and it's not at all clear why.It's not that other languages don't have similar limitations - Python also doesn't have block-local variables, for example. The problem with JS is that is uses syntax that strongly implies that it does have block scope, but then quietly makes it do something unexpected when you try.
Ironically, the only other language that I know of that has the same exact problem is VB (pre-.NET one) - its "Dim" statement can similarly be used anywhere inside a function, including inside loops and other block constructs, but the scope is always the entire function.
And as I'm sure you know, JS now supports block scoped variables through `let` and `const`.