Skip to content
Back to all posts
Technology

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.

3 min read

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

javascript
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());      // 11

The 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

javascript
let status = 'pending';
const showStatus = () => console.log(status);

status = 'complete';
showStatus(); // complete

The 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`

javascript
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, 2

var 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.

javascript
function multiplyBy(factor) {
  return number => number * factor;
}

const double = multiplyBy(2);
console.log(double(7)); // 14

A 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:

javascript
function outer() {
  let value = 1;
  return () => ++value;
}
const next = outer();
console.log(next(), next(), next()); // 2 3 4

A 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