JavaScript Interview Question: What Is a Closure?
Short answer: a closure is a function together with the variables from the scope where it was created. The function keeps access to those variables even after the outer function has returned.
function makeCounter() {
let count = 0; // captured by the inner function
return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2 - 'count' survived after makeCounter returned
Why it matters
- Private state:
countcan't be changed from outside. - Function factories:
const add10 = makeAdder(10). - Callbacks and event handlers that remember their context.
- React hooks: every render's handlers close over that render's props and state.
Follow-up: the loop question
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 3 3 3
for (let i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 0 1 2
With var there's one shared i, so all callbacks see its final value. let creates a new binding for each iteration, so each closure captures its own value.
Bonus point
Closures keep captured variables in memory, so a long-lived closure over a large object can cause a memory leak if it's never released (for example, an event listener that's never removed).
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.