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?
4 Answers
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.
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!
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.
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.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically