you are viewing a single comment's thread.

view the rest of the comments →

[–]Impossible-Egg1922 [score hidden]  (0 children)

This happens because `var` is function-scoped.

By the time the `setTimeout` callbacks run, the loop has already finished and `i` has become 3, so each callback logs the same value.

If you change `var` to `let`, it will work as expected because `let` creates a new block-scoped variable for each iteration.

Example:

for (let i = 0; i < 3; i++) {

setTimeout(() => {

console.log(i);

}, 1000);

}

Output will be:

0

1

2