What is a closure?
EasyJavaScriptScopeClosures
What is a closure, and where do you use one in practice?
TL;DR
A closure is a function together with the variables from the scope where it was created. An inner function keeps access to its outer function's variables even after the outer function has returned. It holds a live reference to those variables, not a snapshot of their values.
Key points
- Every JavaScript function forms a closure. It only becomes interesting when the function outlives its parent scope.
- Common uses: private state (counters, module pattern), factories (
makeAdder(5)), callbacks and event handlers,debounce, and memoization. - React hooks rely on closures. A stale closure happens when a callback captured an old value of state or props.
- Closures keep their variables alive, so a long-lived closure over a large object can leak memory.
Example
js
function makeCounter() {
let count = 0
return () => ++count
}
const next = makeCounter()
next() // 1
next() // 2, and count can't be touched from outsideThe classic trap:
js
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i))
// 3 3 3: one shared i. With let: 0 1 2, a new binding per iterationCommon follow-ups
- What's a stale closure in React? A
useEffectorsetIntervalcallback reading state from the render it was created in. Fix it with the right dependencies, a functional update (setCount(c => c + 1)), or a ref. - Can closures cause memory leaks? Yes, if a long-lived reference (a global listener, a cache) keeps a closure that holds big data.
What interviewers look for
Tip
A one-sentence definition, a real use case (private state or a factory), and the var loop explained correctly.
- Red flag: saying a closure "copies" the values at creation time.