Understanding Closures in JavaScript (With Real Examples)
August 10, 2026 · 7 min read
Every JavaScript tutorial mentions closures right after functions, and most beginners nod along without really getting it — because the textbook definition ("a function that remembers its lexical scope") doesn't click until you've been bitten by one. Here's the version that actually sticks.
The core idea
A closure isn't a special syntax or a feature you turn on. It's just what happens by default whenever a function is defined inside another function — the inner function keeps a live reference to the variables around it, even after the outer function has finished running.
function makeCounter() {
let count = 0;
return function increment() {
count += 1;
return count;
};
}
const counter = makeCounter();
counter(); // 1
counter(); // 2
counter(); // 3`makeCounter` runs once and returns. Normally you'd expect `count` to be gone after that — it's a local variable, the function returned, the stack frame is popped. But `increment` still has access to it, because it closed over `count` when it was created. That's the whole trick: the inner function doesn't get a copy of `count`, it keeps a reference to the actual variable.
Where this actually bites people
The classic bug is a loop that creates functions expecting each one to remember a different value:
for (var i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), 100);
}
// logs 4, 4, 4 — not 1, 2, 3`var` is function-scoped, not block-scoped, so there's only one `i` for the entire loop, and all three closures share a reference to it. By the time the timeouts fire, the loop has already finished and `i` is 4. Switching `var` to `let` fixes it, because `let` creates a fresh binding of `i` for every iteration — each closure gets its own `i` to remember.
Where closures are actually useful
- Private state — the counter example above is real: `count` is only reachable through `increment`, nothing outside can touch it directly.
- Function factories — building a specialized function from a general one, like `const double = multiplyBy(2)`.
- Event handlers and callbacks — anywhere a function is created now but called later, it needs to remember something from when it was created.
Once you see closures as "the default behavior of nested functions" instead of a special feature, half of what looks like magic in React hooks, debounce/throttle utilities, and module patterns stops being mysterious.