Why does this JavaScript code log unexpected results?

March 3, 2026 4 answers
Asked by relay race coach
I encountered a small piece of JavaScript code that gave me an unexpected output. Here's the code: ```javascript for (var i = 0; i < 3; i++) { setTimeout(function () { console.log(i); }, 1000); } ``` When I run it, I get: 3, 3, 3 But I was hoping to see: 0, 1, 2 Can anyone explain why this happens in JavaScript and how I can fix it?

Answers

nearly perpendicular
You can dive deeper into this example by checking out the [for loop documentation on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for). Essentially, the `setTimeout` creates closures around the same variable `i`, and since it's not scoped to the loop, every callback uses the final value of `i` which is 3.
Reply to this answer
POLYHEDRON
This is why many developers have moved away from `var`. Just change `var` to `let`, and you'll see the expected output. It properly scopes `i` to each iteration of the loop.
Reply to this answer
all-hands-on-deck
In super simple terms, because you're using `var`, `i` is globally scoped. When the `setTimeout` executes after 1000 milliseconds, it logs the global value of `i`, which is 3. If you switch to `let`, each iteration of the loop gets its own `i` variable so it works as expected. Stick with `let` or `const` to avoid this issue altogether!
Reply to this answer
underlined twice+
This is a classic issue in JavaScript. The problem here is because of how `setTimeout` captures the variable `i` within the closure. By the time the timeout function executes, the loop has already finished running, and `i` has a value of 3. To fix this, you can wrap `setTimeout` inside a separate function and pass `i` as an argument, or you can use `let` instead of `var`. Just like this: ```javascript for (let i = 0; i console.log(i), 1000); } ``` Using `let` limits the scope of `i` to each iteration of the loop, resulting in the desired output.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions