dev3 ·
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
This prints 3, 3, 3 instead of 0, 1, 2. What is happening?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
This prints 3, 3, 3 instead of 0, 1, 2. What is happening?
var is function-scoped, so there is only one i shared by all three callbacks. The loop finishes (leaving i === 3) before any timer fires, and each closure reads that same variable.
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// 0, 1, 2
let in a for header creates a fresh binding for every iteration, and closures capture that iteration's copy.
for (var i = 0; i < 3; i++) {
setTimeout((n) => console.log(n), 100, i);
}
setTimeout forwards extra arguments to the callback.
for (var i = 0; i < 3; i++) {
((n) => setTimeout(() => console.log(n), 100))(i);
}
A function plus the variables from the scope where it was created. It keeps them alive and can read or change them later.
function counter() {
let n = 0;
return () => ++n;
}
const next = counter();
next(); // 1
next(); // 2
n is private: nothing outside can touch it.
var.const by default, let when you must reassign, avoid var.