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:

1var funcs = [];
2 
3for (var i = 0; i < 3; i++) {         
4    funcs[i] = (function(index) {  
5        return function() {         
6            console.log("My value: " + index);
7        }
8    })(i);
9}

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