The following piece of code will produce 1, 2, 3, 4
const array = [1, 2, 3, 4];
for (let i = 0; i < array.length; i++) {
setTimeout(() => {
console.log(array[i]);
}, 1000);
}
Whereas using var i = 0 in the for loop will produce undefined, undefined, undefined, undefined
const array = [1, 2, 3, 4];
for (var i = 0; i < array.length; i++) {
setTimeout(() => {
console.log(array[i]);
}, 1000);
}
I understand var and let have different scopes but can somebody explain why in the var example, i evaluates to 4 in each iteration?