JS Built-ins
Variablesintermediate

Variables β€” var in loop closures (the classic gotcha)

var in loops: all closures share the same binding

When you create closures inside a for loop with var, all closures share one binding. By the time they run, i is already at its final value.

Challenge: Write varLoopClosure() that:

  1. Creates an array fns
  2. Uses a for (var i = 0; i < 3; i++) loop and pushes () => i to fns
  3. Returns fns[0]() β€” this returns the final value of i (3), not 0
πŸ’‘ Hints (2)
  • β€’ var has function scope β€” all closures point to the same i
  • β€’ After the loop, i === 3