Closures
IntermediateHow a function keeps using the variables around it after the outer function has returned, and why a var loop prints 3, 3, 3.Builds on Scope Chain
Empty
Empty
Empty
Empty
Spaceplay or pause←→previous or next stepRback to the start
Explanation
2 min read
On this page
What is a closure in JavaScript?
A is a function together with the environment it was created in. Every function in JavaScript keeps a link to the scope where it was written, so it can still read and change those variables later, even after the outer function has returned.
Closures are how JavaScript gives you private state, factories like makeCounter, once and
debounce helpers, and callbacks that remember where they came from.
How does a closure keep its variables?
- A function call normally throws its environment away when it returns.
- If a function created inside that call is still reachable (returned, stored, or handed to a timer), the environment is kept alive, because that function still points to it.
- The closure holds the variable, not a snapshot of its value. If the variable changes, the closure sees the new value.
- Each call creates a new environment. Two calls to
makeCounter()give two independentcountvariables.
What mistakes do people make with closures?
Mini example
function createWallet(start) { let balance = start; return { deposit(amount) { balance += amount; }, getBalance() { return balance; }, };} const wallet = createWallet(100);wallet.deposit(50);console.log(wallet.getBalance()); // 150console.log(wallet.balance); // undefined: only the closures can reach itQuick check
What does for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); } print?
Further reading
All steps as text
- Step 1:
The global context starts in its creation phase and sets up every declaration before any line runs.
- Step 2:
makeCounteris stored as a function,counteris reserved but uninitialized, andvar istarts as undefined.Lines 1–13
- Step 3:
makeCounter()is called. Its environment links to global, andcountis reserved in it.Line 9
- Step 4:
countis initialized to 0.Line 2
- Step 5:
The arrow function is created inside
makeCounter, so it keeps a link to makeCounter's environment.Lines 3–6
- Step 6:
makeCounter returns and leaves the stack, but its environment stays: the arrow function still needs
count. That is a closure.Line 9
- Step 7:
counter()runs the arrow function. Its environment links to makeCounter's, where it was created.Line 10
- Step 8:
count++looks upcount: not in its own environment, so one hop out. The real variable becomes 1.Line 4
- Step 9:
It returns 1, and console.log prints it.
Lines 5–10
- Step 10:
The second call finds the same
count, still 1 from last time, and makes it 2.Lines 4–11
- Step 11:
2 is printed.
countis private: only the arrow function can reach it.Lines 5–11
- Step 12:
Now the classic interview loop.
var iis one single variable in the global environment, shared by every iteration.Line 13
- Step 13:
setTimeout stores the callback for later; it does not run now. The callback remembers the variable
i, not its current value 0.Line 14
- Step 14:
ibecomes 1 and a second callback is stored. It links to the same global environment.Lines 13–14
- Step 15:
ibecomes 2 and a third callback is stored.Lines 13–14
- Step 16:
i++makesi3, soi < 3is false and the loop ends. No callback has run yet.Line 13
- Step 17:
The script is done and its context leaves the stack. The global environment stays, and the timers are about to fire.
- Step 18:
The first callback runs.
iis not in its own environment, so the lookup goes out to global and finds 3.Line 14
- Step 19:
It prints 3, not 0.
Line 14
- Step 20:
The other two callbacks follow the same path to the same
i, so each prints 3 too.Line 14
- Step 21:
Output: 1, 2, 3, 3, 3. A closure keeps the variable, not its value; with
let i, each iteration gets its owniand the loop prints 0, 1, 2.