Understanding JavaScript Closures: Scope, State, and Common Mistakes
Learn how JavaScript closures retain lexical scope, build private state, and cause stale values in callbacks, with copyable examples.
TechSilo
Technology writer & developer
A closure is a function that can continue reading variables from the scope where it was created—even after the surrounding function has returned. This behavior is central to callbacks, event handlers, memoization, and stateful utilities.
A closure you can run
function makeCounter(start = 0) {
let count = start;
return {
increment() {
count += 1;
return count;
},
read() {
return count;
},
};
}
const counter = makeCounter(10);
console.log(counter.increment()); // 11
console.log(counter.read()); // 11The returned functions share access to the same count binding. Each call to makeCounter creates a different binding, so two counters do not interfere with each other.
Closures capture bindings, not frozen snapshots
let status = 'pending';
const showStatus = () => console.log(status);
status = 'complete';
showStatus(); // completeThe function looks up the current value of status whenever it runs. But if you create a new local variable for each render or iteration, each closure may refer to a different binding. That distinction helps explain stale-closure bugs.
The loop trap: `var` versus `let`
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// Prints 3, 3, 3
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 0);
}
// Prints 0, 1, 2var gives all callbacks the same function-scoped variable. A let declaration in a for loop creates a fresh binding per iteration. Prefer const and let for modern code.
When closures are useful
- Private state: expose methods without exposing the variable itself.
- Function factories: specialize a generic function with configuration.
- Callbacks: keep access to values available at registration time.
- Memoization: store a cache in a factory function.
function multiplyBy(factor) {
return number => number * factor;
}
const double = multiplyBy(2);
console.log(double(7)); // 14A real pitfall: long-lived references
Closures can keep objects reachable for as long as the closure remains reachable. A permanent event listener that captures a large data structure can prevent that data from being collected. Remove listeners and timers when they are no longer needed; don't assume every closure is a memory leak.
Check your understanding
Before running the following, predict the result:
function outer() {
let value = 1;
return () => ++value;
}
const next = outer();
console.log(next(), next(), next()); // 2 3 4A good mental model is: a function remembers the lexical environment it was created in, not a copy of every value. For help explaining unfamiliar callback code, try the [AI Code Explainer](/tools/ai-code-explainer).
Want to put this into practice?
Explore TechSilo's free developer tools for practical utilities you can use directly in your browser.
Related blog posts
Console.log Alternatives for Efficient JavaScript Debugging
Use browser breakpoints, console.table, console.trace, timing APIs, and structured logs to debug without flooding production consoles.
Read postJavaScript Destructuring Defaults: Avoid Undefined and Subtle Bugs
Use default values in object and array destructuring correctly, including nested options, null behavior, and function parameters.
Read postUnderstanding CSS Specificity: How the Cascade Picks Styles
Understand CSS specificity, source order, cascade layers, :is(), :where(), and practical ways to debug overriding styles.
Read postUnderstanding Virtual DOM Diffing in React
How React compares render output, uses element identity and keys, and decides whether to preserve or reset component state.
Read postUnderstanding WebAssembly: When and How to Use Wasm
Understand WebAssembly modules, JavaScript integration, browser sandboxing, and the workloads where Wasm helps performance.
Read post