Skip to content

Instantly share code, notes, and snippets.

@tatocaster
Last active August 29, 2015 14:15
Show Gist options
  • Save tatocaster/9dab2948de03247c7726 to your computer and use it in GitHub Desktop.
Save tatocaster/9dab2948de03247c7726 to your computer and use it in GitHub Desktop.
js scopes in for loop
/**
* given expression
*/
var run = function(){
var arr = [];
for(var i = 0; i<=10; i++){
arr.push(function(){
alert(i);
});
}
for(var j = 0; j<=10; j++){
arr[j]();
}
}
run();
/* solution*/
var run = function(){
var arr = [];
for(var i = 0; i<=10; i++){
arr.push(
(function(k) {
/* immediately invoked function pattern */
return function() {
alert(k);
};
})(i)
);
}
for(var j = 0; j<=10; j++){
arr[j]();
}
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment