Why does this JavaScript code log unexpected results?

0
10
Asked By CuriousCoder42 On

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

Answered By TechWhiz01 On

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.

Answered By CodeNinja88 On

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!

Answered By DevGuru23 On

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.

Answered By CodeExplorer On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.