Understanding #Closures in Javascript
Closures are quite an advanced feature of Javascript, but you really need to understand them whenever you need to do things like looping through asynchronous operations.
A typical use case is if you wanted to do many Ajax calls in a loop, and you find that the wrong variable value gets sent through, because by the time the Ajax returns the loop has already completed.
Here is a simplified example to demonstrate the problem, I’m using setTimeout instead of Ajax, to make the code more simple;
var arr = [1,2,3,4,5];
for(var i in arr)
{
setTimeout(function()
{
console.log(arr[i])
}, 500);
}
You may think, on first glance, that this code is going to create the output 1 2 3 4 5, but instead, it actually outputs 5 5 5 5 5 ? – here’s the solution:
for(var i in arr)
{
(function(i){
setTimeout(function()
{
console.log(arr[i])
}, 500)})(i);
}
Here, the setTimeout is wrapped in a (function(i){ … })(i) closure, which copies the value of i to the local scope of an inner function. so “i” inside the closure is of different scope to “i” in the for loop, and is in fact a different variable in memory.