Chapter 4 · Closure Camp
Every function leaves home with a backpack.
At Closure Camp, every function call pitches a new campsite. Functions born there carry a rope back to it, so the camp stays standing as long as someone is still holding on. That rope is a closure.
The short answer
A closure is a function together with the variables of the scope it was created in. The function keeps a live reference to those variables, not a copy, so they survive after the outer function returns. That's how counters, private state, and the classic var-in-a-loop bug all work.
What a closure actually is, and why count outlives its function.
Welcome to Closure Camp! Every scope (the area of code where a set of variables lives) is a campsite. The global camp holds makeCounter and counter.
Byte: Welcome to Closure Camp! Every scope (the area of code where a set of variables lives) is a campsite. The global camp holds makeCounter and counter.
Swipe here or tap ▶ to step through1function makeCounter() {2let count = 0;3return function inc() {4count++;5return count;6};7}89const counter = makeCounter();10console.log(counter());11console.log(counter());
Nothing logged yet…
- Green camp = a scope that's currently running
- Purple camp = its call is over, but a closure keeps it alive
- Hiker = a function value
- Rope = the closure: a live link to the camp it was born in
- Glowing crate = the variable that just changed
- Tip: use ← → to step, drag the scene to look around.
Your turn
Predict the output
Interviewers love these. Run the story in your head, pick an answer, and see why.
The classic loop. What logs?
1 / 61for (var i = 0; i < 3; i++) {2setTimeout(() => console.log(i), 0);3}
Before the interview
The cheat sheet
The whole chapter in a few lines, plus the follow-up questions people get caught on.
- 1A closure is a function plus the scope it was created in. Every JavaScript function has one.
- 2Functions remember where they were defined, not where they're called. That's lexical scope.
- 3Closures hold references to variables, not copies of values. If the variable changes, the closure sees the change.
- 4A scope stays alive as long as any function that closed over it is still reachable. After that it can be cleaned up from memory (garbage-collected).
- 5Each call to a function creates a new scope. Two calls to a factory give two independent sets of variables.
- 6
letin aforloop creates a new binding per iteration.varcreates one binding for the whole loop. - 7Uses: private state, factories, memoization,
once, debounce and throttle, partial application, module pattern. - 8Variable lookup walks outward: own scope → enclosing scopes → global. If nothing has the name, it's a
ReferenceError.
Interview traps
›Explain the var loop bug and three fixes.
All callbacks share one var i, which is 3 when they run. Fix with let (new binding per iteration), an IIFE (a function called right where it's defined) that captures i as a parameter, or by passing i in (forEach index, setTimeout's extra args, bind).
›Do closures cause memory leaks?
Only if you keep the function around longer than needed: a long-lived listener or cache that closes over large data keeps that data alive. Remove listeners and drop references when you're done.
›Is every function a closure?
Technically yes: every function captures its lexical environment. In interviews, 'closure' usually means a function that uses outer variables after the outer function has returned.
›Closure vs scope?
Scope is where a name is visible in the code. A closure is the runtime result: a function object that keeps its scope chain alive.
Prefer reading?
The whole chapter, written out
Every step of every story, plus the practice questions with their answers.
The stories
›1. The backpackWhat a closure actually is, and why count outlives its function.
function makeCounter() {
let count = 0;
return function inc() {
count++;
return count;
};
}
const counter = makeCounter();
console.log(counter());
console.log(counter());- line 1Welcome to Closure Camp! Every scope (the area of code where a set of variables lives) is a campsite. The global camp holds makeCounter and counter.
- line 9Calling makeCounter sets up a fresh campsite for that call, with count = 0 inside.
- line 3The inner function inc is born here. Every function leaves home with a backpack: a rope to the camp it was created in. The spec's name for this rope is [[Environment]].
- line 9makeCounter returns inc, and the call is over. Normally its camp would be packed away. But inc's backpack still points at it, so count survives.
- line 4counter() runs inc. count isn't in inc's own scope, so the lookup follows the backpack rope and finds it one camp out. It changes the real variable, not a copy: 0 → 1.
- line 10inc returns 1.
- line 4Second call: same rope, same camp, same count. 1 → 2.
- line 11That's a closure: a function plus the variables it can still reach from where it was born. No code outside can touch count except through counter().
›2. The loop trapvar vs let inside a loop with setTimeout: the classic 3, 3, 3.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 0);
}- line 1var i lives in exactly one place: the global camp. var ignores the loop's block.
- line 2Each setTimeout gets a new arrow function. Its backpack ropes it to where i lives: the global camp.
- line 2i becomes 1. A second arrow, roped to the same camp and the same i.
- line 2And a third. Three arrows, one shared i.
- line 1i++ makes it 3, i < 3 fails, and the loop ends. None of the timers has run yet.
- line 5let is different: each pass of the loop gets a fresh camp with its own j. The arrow is roped to that pass's camp.
- line 6Next pass: a new camp, where j starts as a copy of the last value and then gets incremented. j = 1.
- line 6And j = 2. Three arrows, three separate j's.
- Both loops are done and the call stack is empty, so the timers finally run.
- line 2Timer 1 follows its rope to the global camp. i is 3, because the loop finished long ago.
- line 2Timer 2 reaches the same i: 3 again.
- line 2And 3 again. That's the famous 3, 3, 3.
- line 6Timer 4 follows its rope to its own pass's camp, where j is still 0. Once it's done, nothing points at that camp, so it's cleaned up.
- line 6Timer 5 finds j = 1.
- line 6Timer 6 finds j = 2.
- Same code shape, different scopes. The var arrows share one i; each let arrow closed over its own j. Closures capture variables, not values.
›3. Private stateEvery call builds a new camp. That's how factories and modules hide data.
function makeCounter() {
let count = 0;
return () => ++count;
}
const a = makeCounter();
const b = makeCounter();
a();
a();
console.log(a(), b());
console.log(count);- line 1One factory function. Let's call it twice.
- line 6First call: a new camp with count = 0. The returned arrow is stored as a, roped to that camp.
- line 7Second call: a brand-new camp with its own count = 0, roped to b. Same code, separate state.
- line 8a() bumps the count in camp #1.
- line 9Again: 2. Camp #2 doesn't notice a thing.
- line 10a() makes it 3...
- line 10...while b() follows its own rope and makes its count 1. Two counters, fully independent.
- line 11From outside, count is unreachable: the global camp has no count. The only way in is through a and b. That's how closures give you private state.
Practice questions, answered
›The classic loop. What logs?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}Answer: 3 3 3
There's one var i shared by all three arrows. By the time the timers run, the loop has finished and i is 3.
›Closures see the variable, not a snapshot.
let name = 'Ada';
const greet = () => console.log('Hi ' + name);
name = 'Grace';
greet();Answer: Hi Grace
greet keeps a link to the variable name, not a copy of its value. When it runs, name is already 'Grace'.
›Two counters from one factory.
function counter() {
let n = 0;
return () => ++n;
}
const a = counter();
const b = counter();
a(); a();
console.log(a(), b());Answer: 3 1
Each call to counter creates a new scope with its own n. a's n reaches 3, b's n is 1.
›Shared state between two closures.
function makePair() {
let x = 0;
return [() => x++, () => x];
}
const [inc, get] = makePair();
inc(); inc();
console.log(get());Answer: 2
Both arrows were born in the same call, so they share the same x. Two increments make it 2.
›Fixing the loop without let.
for (var i = 0; i < 3; i++) {
((k) => setTimeout(() => console.log(k), 0))(i);
}Answer: 0 1 2
The IIFE (a function you call right where you define it) runs on every pass and creates a new scope with its own k, copied from i at that moment. Each arrow closes over a different k.
›What does once() do on the second call?
function once(fn) {
let done = false;
return (...args) => {
if (done) return 'skipped';
done = true;
return fn(...args);
};
}
const init = once(() => 'ran');
console.log(init(), init());Answer: ran skipped
done lives in once's scope and persists between calls through the closure. The first call flips it, so the second is skipped.
Go deeper
Read and watch next
ByteTown gives you the picture. These are the sources to read when you want every detail.
Finished the story?
Stamp it on your map. Progress is saved in this browser. Next stop: The Call Center.
Coming soon · Practice Mode
Want drills and mock interviews for this?
Join the waitlist and get early access when it opens.