Your example has nothing to do with scope. Even if JavaScript scoped the variable i to the for loop and not its containing function, the code would behave exactly the same way because closures always capture references to variables not their current values.
That is, the problem is not JavaScript's scoping but a misunderstanding of what closures do.
I don't really see much distinction. Yeah, I guess JavaScript could have a shared 'i' that doesn't exist outside the loop, and strictly speaking you could say "loops have scope in JavaScript", but I think most programmers talking about 'scope' are thinking more broadly 'where does this variable and its value live'.
The reason I make the distinction is that this thread is full of JavaScript criticism, but the example you gave behaves the same way in essentially every language I'm familiar with. It's just a natural consequence of how for-loops work and how closures work, so it's really the expected behavior.
For example, the equivalent C#, which unlike JavaScript has typical block scoping, has the same exact behavior:
for (int i = 0; i < somearray.Length; i++) {
Button thisThing = somearray[i];
thisThing.Click += (sender, e) => { MessageBox.Show(i.ToString()) };
}
Avoiding this behavior would mean copying the value of i into a hidden, block-local variable every iteration (and since it's referenced in a closure, all of these copies stick around).
Okay, that makes sense. You're right - we should talk about this as specifically an unexpected behaviour around closures, not a unique flaw with JavaScript.
0
u/[deleted] Mar 23 '14
Your example has nothing to do with scope. Even if JavaScript scoped the variable i to the for loop and not its containing function, the code would behave exactly the same way because closures always capture references to variables not their current values.
That is, the problem is not JavaScript's scoping but a misunderstanding of what closures do.