Skip to the page

Scope, hoisting and closures · core

Closures

A closure is a function together with the variables of the scope where it was created; the function keeps those variables (live bindings, not copies) and can read and change them after the outer function has returned.

The notes

What you must know

  • Every function remembers the lexical environment it was created in. When it runs later, it looks up outer variables there.
  • Closures capture bindings, not values: if the variable changes later, the closure sees the new value.
  • Each call of an outer function creates a new environment, so two counters made by the same factory have separate state.
  • Real uses: private state, factories, partial application, event handlers that remember config, debounce and throttle timers, memoize caches, once().
  • A closure keeps its environment alive as long as the function itself is reachable. Engines usually keep only the variables the function uses, but a long-lived callback can still hold large data.
  • The classic bug: var in a loop plus an async callback means every callback shares one variable.

The red pen

Common traps: mistake → fix

  • Mistake: A closure is a function inside a function

    Fix: it is a function plus its captured environment; even a module-level function that uses outer variables is a closure.

  • Mistake: Closures copy values when created

    Fix: they capture live bindings; later changes are visible.

  • Mistake: Closures are created only when you return a function

    Fix: one is created every time a function is created.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a closure? Give a real example from your own code, not a counter.
  2. Show private state with a closure. How is it different from #private fields?
  3. Why does setTimeout inside a var loop print 3 3 3?
  4. What is a stale closure in React? Give the setInterval-in-useEffect example.
  5. How can closures leak memory, and how would you find it in a heap snapshot?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview