call(back)

Predict the Output: var and let in a Loop With Timers

What do the timers log? Explain why.

for (var i = 0; i < 3; i++) setTimeout(() => console.log("var", i));
for (let j = 0; j < 3; j++) setTimeout(() => console.log("let", j));

Hints

Hint 1

The callbacks run after both loops finish. Ask which variable each closure sees at that point.

Solution

Show the approach

Answer: var 3 three times, then let 0, let 1, let 2

var gives the loop one shared binding. let gives each iteration its own, and each closure keeps the one it was created in.

Asked at