Skip to the page

Scope, hoisting and closures · mid

Closures in real code: privacy, factories and stale values

In real code closures give you private state, factories and pre-configured callbacks, and they cause two common bugs: stale values (a callback reads a variable from an old render or call) and memory that stays alive longer than needed.

The notes

What you must know

  • Module pattern: a function returns a public API and keeps the rest private in its scope. Today ES modules give file-level privacy and classes have #private fields.
  • Factory functions such as createStore(reducer) return functions that share hidden state.
  • Partial application with closures: const logAt = (level) => (msg) => console.log(level, msg).
  • Stale closure in React: an interval or effect created on the first render keeps that render's state. Fixes: functional updates (setCount(c => c + 1)), correct dependencies, a ref, or useEffectEvent (React 19.2).
  • Closure privacy vs #private: both are private; closures create functions per instance, while #private works with shared prototype methods and supports the brand check #x in obj. TypeScript 'private' is compile-time only.
  • Memory: listeners and timers that close over big objects or DOM nodes keep them alive. Remove listeners (or use an AbortSignal), clear timers, and unsubscribe.

The red pen

Common traps: mistake → fix

  • Mistake: Stale closures are a React bug

    Fix: it is normal JavaScript: each render creates new closures over that render's values.

  • Mistake: Closure privacy and #private are identical

    Fix: #private has engine-enforced brand checks and doesn't need per-instance functions.

Easy to hard

Questions interviewers ask, easy to hard

  1. Show the module pattern. What replaced it?
  2. Why does setInterval inside useEffect with [] show the same count forever? Fix it three ways.
  3. Compare closure privacy, #private fields and TypeScript private.
  4. A dashboard gets slower after an hour of use. How could closures be involved, and how do you check?

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