JavaScript - Lesson - Var Scope
// Topic: Var Scope
// Lesson: Don't create functions in a loop.
// Why?: The person variable is scoped to the block, not the for loop.
// Every function will use the last value of person.
JavaScript
// Topic: Var Scope
// Lesson: Don't create functions in a loop.
// Why?: The person variable is scoped to the block, not the for loop.
// Every function will use the last value of person.
//----------------------------------------------------
var callbacks = [];
var people = ['john', 'mike', 'jason'];
for(var i=0; i<people.length; i++){
var person = people[i];
callbacks.push(function(){
console.log(person);
});
}
callbacks.forEach(function(callback){
callback();
});