JavaScript theorytheory 0/50 · 0%
Fundamentals · easy

11. Scope and closures

Why an inner function remembers its outside.

A closure is a function together with the variables it captured where it was defined. That is how you build counters, caches, memoisation and private state without classes.

function makeNonce(start = 0) {
  let n = start;
  return () => n++;
}
const next = makeNonce(5); // 5, 6, 7…

Closures are also the reason a stale variable captured in a callback keeps an old value — watch for it in event handlers.

Check your understanding

  1. 1. What does a closure capture?

  2. 2. What is a common use of closures?

  3. 3. Does a closure keep captured variables alive?