why does this happen??? #189150
Replies: 2 comments
-
|
var is function scoped so all 5 callbacks point to the same i and by the time they fire the loop is done and i is 5 they all read the same variable not their own copy hope it helps!!! |
Beta Was this translation helpful? Give feedback.
-
|
The behavior happens because of two things working together:
Consider the code: for (var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}The loop runs immediately and finishes almost instantly.
All callbacks reference the same i variable, so they all print: Fix (Use let) let is block-scoped, so each loop iteration gets its own i. Output: Alternative (pre-ES6) Capture the value using an IIFE: Here the function parameter creates a new scope, preserving the value of i for each callback. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Body
for (var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
Why does this print 5 five times instead of 0, 1, 2, 3, 4?
Guidelines
Beta Was this translation helpful? Give feedback.
All reactions