javascript closures are fun

Jonathan

I really like closures in javascript. I really miss them when I am doing work in Java,  but sometimes when I use them I get a little messed up. Take the following example:

var i;
var objects=[1,2];
for (i=0;i < objects.length;i++) {
    var callback=function() {
        console.log(objects[i]);
    };
    doSomethingAsynchronous(callback);
}

Then you would might expect “1″ and “2″ to be logged when the callbacks come back. This is wrong, instead “2″ and “2″ are logged.

Due to the nature of closures, “i” is one of variables that fall into the scope of the closure by reference, not by value. So, when the value of “i” is updated in the for loop, the current (latest) value is then referenced later on by the closures. So the last item in the list is the item that is accessed.

The way to get around this is to modify the above code slightly, to make the item that you want an argument of a function, rather than accessed through closure scope. Eg:

var i;
var objects=[1,2];
function doSomethingAsynchronousAndLogIt(value) {
    var callback=function() {
        console.log(value);
    };
    doSomethingAsynchronous(callback)
}
for (i=0;i < objects.length;i++) {
    doSomethingAsynchronousAndLogIt(objects[i]);
}

Leave a Reply