Why does using var inside a loop behave differently from let when using setTimeout()? #212990
🏷️ Discussion TypeQuestion 💬 Feature/Topic AreaCode Search and Navigation BodyI'm trying to understand JavaScript's variable scope and asynchronous behavior. Consider these two examples: Example A: for (var i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}Output: Example B: for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}Output: Why do these two examples produce different outputs? Specifically:
|
Replies: 1 comment
|
The difference comes from how JavaScript handles variable scope. var is function-scoped, meaning all loop iterations share the same variable i. By the time the callbacks execute, the loop has already finished and i is 3. Therefore, all callbacks print 3. On the other hand, let is block-scoped. In a for loop, JavaScript creates a separate binding for each iteration, allowing each callback to retain its corresponding value. setTimeout() schedules the callbacks to execute later, after the synchronous loop has finished. That's why var produces 3, 3, 3, while let produces 0, 1, 2. |
The difference comes from how JavaScript handles variable scope.
var is function-scoped, meaning all loop iterations share the same variable i. By the time the callbacks execute, the loop has already finished and i is 3. Therefore, all callbacks print 3.
On the other hand, let is block-scoped. In a for loop, JavaScript creates a separate binding for each iteration, allowing each callback to retain its corresponding value.
setTimeout() schedules the callbacks to execute later, after the synchronous loop has finished.
That's why var produces 3, 3, 3, while let produces 0, 1, 2.