Created
December 16, 2010 10:48
-
-
Save novemberborn/743278 to your computer and use it in GitHub Desktop.
Closures inside for-loops
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
var results = []; | |
for(var i = 0; i < 10; i++){ | |
// Bad: | |
// results.push(function(i){ return i; }); | |
// 'Good': | |
results.push((function(i){ | |
return function(){ return i; }; | |
})(i)); | |
} | |
console.log(results.map(function(f){ return f(); })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment