Using Javascript closures in for loops to keep callbacks from overriding the iterator

February 5th, 2013 by admin Leave a reply »

The problem: You have a for loop in javascript that is executing and you are losing your pointer to the iterator. You can write something like below, wrap your stuff in a closure like so:

var funcs = [];

for (var i = 0; i < 3; i++) {          
    funcs[i] = (function(index) {   
        return function() {          
            console.log("My value: " + index);
        } 
    })(i);
}

Since there is no block scope in JavaScript – only function scope – by wrapping the function creation in a new function, you ensure that the value of “i” remains as you intended. This drove me crazy till I understood how things work in Javascript, now life is good, hope this helps someone.

Advertisement

Leave a Reply