What is a closure and when would you use one?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
A closure is a function bundled with references to its outer lexical scope, so it remembers and can use variables from where it was defined — even after that outer function has returned.
Detailed explanation
Functions in JavaScript capture the environment they were created in, not a copy of the values. When an inner function survives beyond its outer function's lifetime (returned, passed as callback, stored), it keeps a live reference to those variables. This enables private state without classes: counters, caches and module patterns all rely on closures for encapsulation. Closures power event handlers that remember configuration, memoization wrappers, once() helpers, and are the foundation of how hooks like useState keep values between renders in React. The classic gotcha is creating closures inside loops with var: every iteration shares one variable, so all callbacks print the final value; let creates a fresh binding per iteration and fixes it.
Example
function createCounter() {
let count = 0; // captured by closure
return {
increment: () => ++count,
value: () => count,
};
}
const counter = createCounter();
counter.increment();
counter.increment();
console.log(counter.value()); // 2 — count lives on
// Classic loop pitfall:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log('var:', i)); // 3, 3, 3
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log('let:', j)); // 0, 1, 2
}Interview tip
Define it crisply ('function + its lexical scope'), then immediately demonstrate with private counter code and mention the var-in-loop gotcha. That trio covers 90% of follow-up questions.
Common mistakes
- Saying closures 'copy' outer variables — they hold live references.
- Not knowing a practical use case like memoization or private state.