What is a closure and why is it useful?
Quick answer
A function that keeps access to variables from the scope where it was defined, even after that scope has returned.
In detail
Thanks to lexical scope, an inner function retains a live reference to its outer variables. Closures power data privacy (the module pattern), function factories, memoization caches, and the timers inside debounce/throttle. The cost: captured variables aren't garbage-collected while the closure lives.
1function counter() {
2 let n = 0;
3 return { inc: () => ++n, get: () => n };
4}
5const c = counter();
6c.inc(); c.inc();
7c.get(); // 2 — n is private, kept alive by the closureWhy interviewers ask this: The most common JS interview question — reveals depth on scope.
Common follow-up questions
- →How can a closure cause a memory leak?
- →Write a function that runs only once.
This is 1 of 118+ questions in the JavaScript Interview Kit
Get every question with detailed answers, follow-ups and real code — plus coding challenges and a last-minute revision sheet. One-time payment, instant access.
⚡ Get the JavaScript Interview Kit → ₹299