To my understanding, if the loop variable of a for loop is defined with var, then any change on that variable is applied globally. for example:
var printNumTwo;
for (var i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
In the above code, 3 will be printed into the console. Because in the last iteration the variable i will equal to 3. Therefore when printNumTwo is called, the update i will be returned.
However if I use let this is not the case and the following behavior happens:
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
The above code will print 2.
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
i = 3;
}
}
console.log(printNumTwo());
however, the above code prints 3.
What is the reason for this?
source: The first two code blocks are from here.
>Solution :
In the first example, var scopes i to the function, so at the end of the loop i++ changes i from 2 to 3 and the loop stops. The only i is now 3 and printNumTwo returns i which is 3.
In the second example let scopes i to the block, so the function assigned to printNumTwo closes over it. The last time the body of the loop runs, i is 2 and printNumTwo returns i which is 2. (A new i is created with the value 3 but no function is created that uses it).
In the third example, let scopes i to the block and the same thing happens except you have i = 3; which changes every i to 3. So the last function that is created (as well as the previous ones which are overwritten) returns i which is 3.