What is a closure in JavaScript and why is it useful?
Quick answer
A closure is a function that keeps access to the variables of the scope where it was created, even after that outer function has finished running.
Every function in JavaScript carries a reference to the lexical environment it was defined in. When an inner function is returned or passed elsewhere, that environment stays alive for as long as the function can be called, so the inner function can still read and update the outer variables.
Closures give you private state without classes, power patterns such as memoization, debounce and once-only functions, and make callbacks and React hooks work. The trade-off is memory: anything captured by a closure cannot be garbage collected while the closure is reachable.
function createCounter() {
let count = 0; // private, not reachable from outside
return function () {
count += 1;
return count;
};
}
const next = createCounter();
next(); // 1
next(); // 2Key points
- A closure = a function plus its surrounding scope
- Used for private state, factories, callbacks and memoization
- Captured variables stay in memory while the closure is reachable
Questions interviewers ask next
- Why does a loop with var and setTimeout print the same number?
- How can closures cause memory leaks?