A closure is a function that remembers the variables from the scope where it was created, even after that scope has finished running. It sounds abstract until you see it — and then you realise you have been using closures since your first event listener.
The simplest example is a counter. The inner function remembers count long after createCounter has returned:
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
count is not a global, and nothing outside the returned function can touch it. That is private state in a language with no private keyword — and it is how modules, plugins, and most libraries protect their internals.
Every event listener is a closure. This handler remembers buttonId from the loop where it was created:
const buttons = document.querySelectorAll(".like-btn");
buttons.forEach((button) => {
let likes = 0;
button.addEventListener("click", () => {
likes++;
button.textContent = `Liked (${likes})`;
});
});
Each button gets its own likes variable, because each handler closes over a different call to the forEach callback. Before let and forEach, the classic bug was using var in a for loop — all handlers shared one variable and every button showed the last value.
Closures also power the factory pattern: one function that stamps out specialised versions of another:
function multiplyBy(factor) {
return (number) => number * factor;
}
const double = multiplyBy(2);
const triple = multiplyBy(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
double remembers factor = 2 and triple remembers factor = 3, from the same code. This is how middleware, validators, and curried functions work in real codebases.
The one real danger is memory: a closure keeps its whole scope alive. If you attach a closure to a DOM node and never remove it, the variables it captured stay in memory too. Remove listeners when elements are destroyed, and do not capture huge objects you do not need.
Ways to extend it: build a tiny module with private state and public methods, rewrite a callback-heavy function with a closure that caches results (memoisation), or read the source of a small library and spot the closures holding its state. Once closures click, callbacks, promises, and React hooks all start making sense — they are the same idea in different clothes.
Top comments (0)