Hacker News new | ask | show | jobs
by int_19h 3556 days ago
Any time you have a closure that captures the hoisted variable. Most often, this happens with loops. Say, someone might start with this:

  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.

1 comments

Ok, thanks. I would call that a problem with not having block scope, not a problem with hoisting. Not trying to be pedantic; I was just confused about how hoisting could be such a problem. A language could have variable/function declarations hoisted to the top of block scope rather than the top of function scope.

And as I'm sure you know, JS now supports block scoped variables through `let` and `const`.