What is a closure?

A closure is a function together with the variables from the scope where it was created; the function keeps access to those variables even after the outer function has returned.

Every function in JavaScript remembers its lexical environment, the variables in scope where it was written. When an inner function is returned or passed somewhere else, that environment stays alive as long as the function can still be called.

What closures are used for

  • Private state: variables that only the returned functions can read or change (counters, caches, module internals).
  • Function factories: makeMultiplier(3) returns a function that remembers 3.
  • Callbacks and event handlers that need data from when they were set up.
  • Memoization, debounce, throttle, once: they all keep state in a closure.
  • React hooks rely on closures; "stale closures" are a common bug there.

Things to watch for

  • Shared variables in loops: with var, all closures share one variable. Use let.
  • Memory: a closure keeps its variables alive. Holding onto large data inside long-lived closures (e.g. event listeners never removed) can cause leaks.
  • Stale values: a closure sees the variable, not a snapshot. If the variable changes, the closure sees the new value; if a new variable is created each render (as in React), an old closure keeps seeing the old one.

Interview tip

Show a counter with private state and explain why count is still alive after createCounter returns.

Code example

js
1function createCounter() {
2 let count = 0; // private: only the functions below can reach it
3 return {
4 increment: () => ++count,
5 decrement: () => --count,
6 get value() {
7 return count;
8 },
9 };
10}
11
12const counter = createCounter();
13counter.increment();
14counter.increment();
15console.log(counter.value); // 2
16console.log(counter.count); // undefined - not reachable from outside
17
18// Function factory
19const makeMultiplier = (factor) => (n) => n * factor;
20const triple = makeMultiplier(3);
21console.log(triple(5)); // 15
22
23// once(): closure state used to run something a single time
24function once(fn) {
25 let done = false, result;
26 return (...args) => (done ? result : ((done = true), (result = fn(...args))));
27}
28const init = once(() => {
29 console.log("initialised"); // runs only the first time
30 return 42;
31});
32console.log(init(), init()); // 42 42

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app