DEV Community

Rohit Surage
Rohit Surage

Posted on

Var vs Let

Good stuff:

**for (var i = 0; i < 3; ++i) {
setTimeout(() => console.log(i), 1000); // returns 3 three times
}

for (let i = 0; i < 3; ++i) {
setTimeout(() => console.log(i), 1000); // returns 0 1 2
}**

This is because var creates a single binding at the function scope, so after a one-second timeout the loop has already run its course, hence you get 3 three times. By using let you bind the variable at the block scope (loop), so it returns the values you expected since i refers to the value at that loop iteration.

Top comments (0)