What is a closure in JavaScript? Show a practical use, and one bug closures can cause.
Show hints
- Ask: which variables can the inner function still see after the outer one returns?
Show the explanation
Model answer. A closure is a function together with the variables from the scope where it was created. The inner function keeps access to those variables even after the outer function has returned.
function makeCounter() {
let count = 0; // private: nothing outside can touch it
return {
next: () => ++count,
reset: () => { count = 0; },
};
}
const c = makeCounter();
c.next(); c.next(); // 2Practical uses:
- Private state, as above (data hiding without classes).
- Function factories:
const add5 = makeAdder(5). - Callbacks and event handlers that remember configuration.
- Memoisation caches.
A bug they can cause: closures capture variables, not values. With var in a loop, every callback shares one variable and sees its final value. With let, each iteration gets a fresh binding. Closures can also keep large objects alive longer than expected if a long-lived callback references them.
Original UniCircle question. Last reviewed 22 Oct 2026.
