Skip to content

Instantly share code, notes, and snippets.

@parambirs
Created December 13, 2015 08:25
Show Gist options
  • Save parambirs/2e3e2c36c51a9e8835f5 to your computer and use it in GitHub Desktop.
Save parambirs/2e3e2c36c51a9e8835f5 to your computer and use it in GitHub Desktop.
Closure - problem and solution
var result = [];
for (var i=0; i < 5; i++) {
result.push(function () { return i }); // (1)
}
console.log(result[1]()); // 5 (not 1)
console.log(result[3]()); // 5 (not 3)
for (var i=0; i < 5; i++) {
(function () {
var i2 = i; // copy current i
result.push(function () { return i2 });
}());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment