I was reading about closures in JavaScript when I came upon this problem:
for (var i = 0; i < 3; i++) {
setTimeout(function () {
console.log(i);
}, 1000); // 1 second delay
}
My expected output is:
*loop finishes
0
1
2
Why is it:
*loop finishes
3
3
3
I don't understand how changing var to let fixes the problem, as they are both defined in the for-loop, so their scope should be the same.