JavaScript theorytheory 0/50 · 0%
Functions · medium

27. Closures and scope

Functions remember where they were created.

A closure captures the variables of its defining scope, keeping them alive after the outer function returns. That powers private state, memoisation and counters.

function nonce(start = 0) {
  let n = start;
  return () => n++;
}

Beware capturing a loop variable declared with `var` — every closure sees the same binding; `let` gives one per iteration.

Check your understanding

  1. 1. What does a closure capture?

  2. 2. Why does `var` misbehave in loops?

  3. 3. A common closure use is: