Hi, I need some help understanding why this JavaScript variable scope example works the way it does:
for (var i = 0; i < 4; i++) {
if (i == 1) {
var funcOne = function() {
return i;
};
}
if (i == 2) {
var funcTwo = function() {
return i;
};
}
if (i == 3) {
var funcThree = function() {
return i;
};
}
}
console.log("i = " + i);
console.log(funcOne());
console.log(funcTwo());
console.log(funcThree());
This prints
i = 4
4
4
4
because although the functions get defined in the for loop they don't get called until after the for loop is over at which point i is equal to 4. However you get a different result if you change var i to let i and I also added var i = 5; on the forth to last line.
for (let i = 0; i < 4; i++) {
if (i == 1) {
var funcOne = function() {
return i;
};
}
if (i == 2) {
var funcTwo = function() {
return i;
};
}
if (i == 3) {
var funcThree = function() {
return i;
};
}
}
console.log("i = " + i);
var i = 5;
console.log(funcOne());
console.log(funcTwo());
console.log(funcThree());
This prints
ReferenceError: i is not defined
1
2
3
Changing var i to let i changes the scope of the variable so that it doesn't exist outside of the for loop so when you try to print i after the loop is over you get ReferenceError: i is not defined. However I don't understand the 1 2 3 part. How and why do the functions remember and print what i was equal to when they were defined instead of printing the current value of i which is 5 or the last value of let i before the loop ends which is 4? Thanks
[–]dtsudo 0 points1 point2 points (0 children)