The #1 JavaScript interview topic. One sentence: a closure is a function that remembers the variables from where it was created, even after that place has finished running.
The canonical example
function counter() {
let count = 0; // private variable
return function () {
return ++count; // still sees count!
};
}
const inc = counter();
inc(); // 1
inc(); // 2 โ count survives between callscounter() finished executing, yet count lives on โ captured in the returned function's closure. Nothing outside can touch it: that is genuine privacy.
Where you already use closures
- Every event handler that references outer variables
- Debounce/throttle implementations
- React hooks โ
useStateworks because of closures - Module patterns hiding internal state
Interview follow-up
"What is the downside?" โ memory: closures keep captured variables alive, so giant objects captured accidentally cannot be garbage-collected.
Practice with the 100 JS interview questions.