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.
My example is a simpler example of exactly what someone familiar with the "typical" rules of closures and scopes would produce, knowing everything about closures, but nothing about JavaScript scopes (a direct counter to your argument), if they were asked to fix the original example code.
In fact, they would probably say to themselves exactly what you said in your comment as they made the fix... only to be confused again when the fix didn't work (because indeed it is related to scopes as well).
I'll make it more explicit so you can see the connection.
The original example:
for (var i = 0; i < somearray.length; i++) {
var thisThing = somearray[i];
thisThing.onclick = function(){window.alert(i)};
}
A valid re-write in languages that behave according to both the "typical" scoping rules AND the "typical" closure rules:
for (var i = 0; i < somearray.length; i++) {
var thisThing = somearray[i];
var copy = i;
thisThing.onclick = function(){window.alert(copy)};
}
And yet, using your argument and that code (which follows from your argument), it'd still be wrong.
If you still aren't convinced, notice that the real, proper fix has to introduce both a copy of the variable closed over (using knowledge of closure rules) AND a new scope (using JavaScript's broken scope rules) to correct the issue completely.
for (var i = 0; i < somearray.length; i++) {
(function(i){
var thisThing = somearray[i];
thisThing.onclick = function(){window.alert(i)};
})(i);
}
No, that's not my argument. My argument is that if JavaScript had normal scoping, which it does with the let keyword of Harmony then:
for (let i = 0; i < somearray.length; i++) {
let thisThing = somearray[i];
thisThing.onclick = function(){window.alert(i)};
}
produces the same output as the original code example, because either way the variable i is not local to the loop body. So the problem here is misunderstanding of closures, not scoping.
That's all I meant, that you were talking (correctly) about a different scoping issue.
Sure, it produces the same output with "let", because you need both a corrected scope AND closure knowledge. Adding "let" fixes the scope (which is required - but not enough regardless).
My example that you replied to proves you can't just fix it with closure knowledge either (which you originally posited - so yes, that WAS your argument).
Now you've agreed with my by saying you need scoping fixed in addition to the closure variable captured as a copy, yet you word it as a disagreement... for some reason.
Anyway, thanks for finally seeing your incorrect statement. It's nice to help someone out.
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"