Functions has access to it own lexical as well outer environment but it's not working or maybe I don't understand why it's working like that.
Here is the code
function makeArmy() {
let shooters = [];
let i = 0;
while (i < 10) {
let shooter = function() {
console.log( i );
};
shooters.push(shooter);
i++;
}
return shooters;
}
let army = makeArmy();
// all shooters show 10 instead of their numbers 0, 1, 2, 3...
army[0](); // 10 from the shooter number 0
army[1](); // 10 from the shooter number 1
army[2](); // 10 ...and so on.
Fixed code
while (i < 10) {
let j = i; // added variable to while loop (lexical environment)
let shooter = function() {
alert( j );
};
shooters.push(shooter);
i++;
}
But why don't it work like this when i define variable with J inside the function! Shooter function has it's own lexical environment.
while (i < 10) {
let shooter = function() {
let j = i; // define J inside function but still it gives 10 why?
console.log( j );
};
shooters.push(shooter);
i++;
}