The Javascript Closure Problem
Swami Gulagulaananda said:
"Closure is very important in broken relationships... Also in JavaScript"
I was trying to write a fairly simple piece of code where I would create an array of functions in JavaScript. There was a loop and a function would be generated in each iteration such that the body of the function had a dependency on the loop counter. What happened finally was that every function in the loop was the same as the last function. I was bewildered. I understood that it was because of some reference issue but could not come up with a solution easily.
Here is a simple piece of code:
I was expecting a[0]() to give 0, a[1]() to give 1 and so on. But I was getting 3 each time. How do you solve this?
After breaking my head for some time (despite knowing it was something to do with Closures) I posted the question on Stackoverflow. Try solving this problem by yourself before seeing the solution.
Here's the solution:
"Closure is very important in broken relationships... Also in JavaScript"
I was trying to write a fairly simple piece of code where I would create an array of functions in JavaScript. There was a loop and a function would be generated in each iteration such that the body of the function had a dependency on the loop counter. What happened finally was that every function in the loop was the same as the last function. I was bewildered. I understood that it was because of some reference issue but could not come up with a solution easily.
Here is a simple piece of code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = []; | |
for (var i = 0; i < 3; i++) { | |
a.push(function() { | |
console.log(i); | |
}) | |
} | |
a[0]() |
I was expecting a[0]() to give 0, a[1]() to give 1 and so on. But I was getting 3 each time. How do you solve this?
After breaking my head for some time (despite knowing it was something to do with Closures) I posted the question on Stackoverflow. Try solving this problem by yourself before seeing the solution.
Here's the solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = []; | |
for (var i = 0; i < 3; i++) { | |
(function(i){ | |
a.push(function() { | |
console.log(i); | |
}) | |
})(i); | |
} | |
a[0]() |
Comments