JavaScript Closure in Loop

April 3rd, 2010
Bookmark and Share

JavaScript anonymous functions are really a bliss, and they way the help you write neat, flexible and dynamic code is simply amazing. I always admire them whenever I use them.

But they don’t work in loops as neatly as in some other languages where the variables are scoped to the block level (like C#). In JavaScript, they simply take the last value. Let’s see a quick example:

for (var i=0; i<5; i++)
    document.getElementById("someobject_"+i).onclick = function()  {alert(i)}

Now if you click on any of the object (someobject_1,  someobject_2, etc) you will get the alert of last value of the “i” which in this case would be 5. The reason is that in the JavaScript closure only the last value is stored for local variables.

But what if you really what to do something similar i.e. set the anonymous function values in the loop. Fortunately, it’s not as complex as it sounds at first. The basic concept is that you need to make the variables block specific (some what similar in C#). One simple way to do this is call another function, pass it the value, and then create an anonymous function in that function to do the job. A bit tricky, but works very well. So here is something similar for the above function:

function getValue(value)
{
    return  function() {alert(value);}
}
 
for (var i=0; i<5; i++)
    document.getElementById("someobject_"+i).onclick =getValue(i);

It’s a bit tough to grasp at start, but once you master that skill, you will love it even more.

Tags: , ,

Leave a Reply