Gang Kenari’s open house is the loop: every turn sets a setTimeout, and Rizal, Yanti and Jaya open their boxes. With var and with let, which box do they open…
Why it matters
This is JS’s most famous closure gotcha: it shows up in interviews, in event listener loops, in setTimeout. Understanding it means understanding what a binding is, and why let/const replaced var.
The key idea
var shares one binding, let makes a new binding every turn
Common mistakes
Every callback in the loop prints the last number, not each turn’s own Switch to let in the for’s head, done. There is almost no reason to use var anymore.
Assuming .forEach has the same gotcha It does not: each forEach callback has its own parameter, a separate binding. Safe from the start.
Feeling that let is slower than var Per-turn bindings are optimized by the engine; the difference is irrelevant. Correctness beats micro-optimization.
Try it in this playground
var in the loop, run it to the end All three callbacks print 3: they all open the one i box in the hall.
Switch to let, run it again It prints 0, 1, 2: every turn has its own i box.
Try forEach Safe: every call has its own parameter i.
Read at once, with no callback Even with var it prints 0, 1, 2: the gotcha only shows when the read is deferred.