const array = [1, 2, 3, 4];
for (var index = 0; index < array.length; index++) {
setTimeout(() => {
console.log("I am at index " + index);
});
}
When I use the "var" keyword in the for loop I get the output
I am at index 4
I am at index 4
I am at index 4
I am at index 4
But When I use the "let" keyword in the for loop,
const array = [1, 2, 3, 4];
for (let index = 0; index < array.length; index++) {
setTimeout(() => {
console.log("I am at index " + index);
});
}
I am at index 0
I am at index 1
I am at index 2
I am at index 3
Can anyone tell me what's happening here?