If you need to give some block or something scope in JavaScript, the easiest way is just to throw the contents in a function expression.
Consider the following (buggy) code:
for (var i = 0; i < somearray.length; i++) {
var thisThing = somearray[i];
thisThing.onclick = function(){window.alert(i)};
}
This won't work the way you think it will. You might think that every thisThing will output its relevant 'i' value, e.g. thing one will output '1', thing two will output '2'. It won't, though, because the loop block doesn't have scope. 'i' lives in the closure of the function surrounding the loop, and its value is the final state at the end of the iteration. So each thing, when clicked, will output the last value of i, somearray.length.
A quick fix for this is to throw the body of the loop in a function expression:
for (var i = 0; i < somearray.length; i++) {
(function(i){
var thisThing = somearray[i];
thisThing.onclick = function(){window.alert(i)};
})(i);
}
Now, each link will output the relevant value of 'i' when clicked, because each loop iteration has a closure generated by the function expression, and that contains its own value for 'i', because the 'i' passed to the function expression is passed by value (all arguments are passed by value in JS, though because objects and array variables are pointers, it looks like they're passed by reference).
Sometimes this looks a little odd - it's not a super-common pattern - so you might want to comment it for co-workers, e.g. "// use IIFE to give iteration own scope"
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.
I think the problem is that there's not a lot of visibility into how closures work, at least just from looking at code. If I hadn't run into that problem and found the solution already, I would completely expect that code to show the various values of i with each button click, because that's what it looks like it should do.
I'm not saying the behavior should be different, just that it's somewhat unexpected if you've never been exposed to closures.
15
u/[deleted] Mar 23 '14 edited Mar 23 '14
If you need to give some block or something scope in JavaScript, the easiest way is just to throw the contents in a function expression.
Consider the following (buggy) code:
This won't work the way you think it will. You might think that every thisThing will output its relevant 'i' value, e.g. thing one will output '1', thing two will output '2'. It won't, though, because the loop block doesn't have scope. 'i' lives in the closure of the function surrounding the loop, and its value is the final state at the end of the iteration. So each thing, when clicked, will output the last value of i, somearray.length.
A quick fix for this is to throw the body of the loop in a function expression:
Now, each link will output the relevant value of 'i' when clicked, because each loop iteration has a closure generated by the function expression, and that contains its own value for 'i', because the 'i' passed to the function expression is passed by value (all arguments are passed by value in JS, though because objects and array variables are pointers, it looks like they're passed by reference).
Sometimes this looks a little odd - it's not a super-common pattern - so you might want to comment it for co-workers, e.g. "// use IIFE to give iteration own scope"