Tag: variable
Fun with JavaScript Closures + Scoping
by Warlock on Jul.10, 2010, under Javascript
It’s easy to forget that variable scoping in JavaScript is at the function level and not a the block level like what you get with C/C++/C#/Java/etc. This can have some counter intuitive implications when you’re dealing with closures. Consider the following example:
var closure;
for(var i = 0; i <= 5; i++) {
var x = i * i;
if( i == 1 ) {
closure = function() { alert(x); };
}
}
closure();
What do you think the output of the alert box will be? At first blush it's easy to think it will be 1 because the variable x is declared within the for loop.
In reality, though, the output is 25 because despite the variable declaration in the for loop, the code is functionally equivalent to this:
var closure;
var x;
for(var i = 0; i <= 5; i++) {
x = i * i;
if( i == 1 ) {
closure = function() { alert(x); };
}
}
closure();
This is important to remember when working with closures in loops.
So how do solve this problem? Manually create a new scope by creating and invoking an anonymous function.
var closure;
for(var i = 0; i <= 5; i++) {
var x = i * i;
if( i == 1 ) {
(function(x) {
closure = function() { alert(x); };
})(x);
}
}
closure();
With the newly introduce lexical scope, the program returns 1 as one would expect.