Home > Uncategorized > Understanding #Closures in Javascript

Understanding #Closures in Javascript

Understanding-JavaScript-Closure

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.

 

 

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: