What is a closure?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
A closure is a function together with the scope it was created in. Because the function keeps a reference to that scope, the variables stay alive even after the outer function has returned.
function counter() {
let count = 0; // would normally disappear when counter() returns
return () => ++count; // but the returned function still references it
}
const next = counter();
next(); // 1
next(); // 2
Every function in JavaScript is a closure — the term is only interesting when the inner function outlives the outer one.
Why they exist
Scoping is lexical: a function can see the variables where it was written. Keeping that scope alive is the only way that guarantee can hold once the function is passed elsewhere.
What you use them for
- Private state.
countabove cannot be reached from outside; only the returned function can change it. - Factory functions that produce configured behaviour:
const add5 = makeAdder(5). - Callbacks that remember context — an event handler still knowing which item it belongs to.
- Memoisation, holding a cache between calls.
- Partial application, fixing arguments now and supplying the rest later.
function once(fn) {
let called = false, result;
return (...args) => called ? result : (called = true, result = fn(...args));
}
Two things to remember
Closures capture references, not copies. A var loop counter shared by three callbacks logs the final value three times; let gives each iteration its own binding.
And the captured scope cannot be collected while the closure lives, so a long-lived callback holding a large object keeps it in memory — the usual source of leaks in event handlers.
