From what I understand, when the loop variable of a for loop is declared using var, any changes made to that variable are reflected globally. For example:
var printNumTwo;
for (var i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
In the code snippet above, the console will display 3. This is because in the final iteration, the variable i will be equal to 3. Therefore, when calling printNumTwo, the updated value of i will be returned. However, this behavior changes when using let:
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
The second code snippet will output 2.
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
i = 3;
}
}
console.log(printNumTwo());
Surprisingly, the third code snippet prints 3. What could be the reason behind this difference?