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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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
- Show the module pattern. What replaced it?
- Why does setInterval inside useEffect with [] show the same count forever? Fix it three ways.
- Compare closure privacy, #private fields and TypeScript private.
- A dashboard gets slower after an hour of use. How could closures be involved, and how do you check?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.