JavaScript closures and scope explained with small examples
What a closure is, why let and const are block-scoped while var isn't, the classic loop bug, and how closures give you private state, counters and memoised functions.
Closures sound advanced, but you use them every time a callback reads a variable from outside itself. Understanding them explains a whole family of bugs, and a handful of very useful patterns.
Scope: where a name is visible
const venue = "Harbor Lights"; // module scope
function sell(count) {
const price = 12; // function scope
if (count > 4) {
const discount = 0.1; // block scope: only inside these braces
}
// discount is not visible here
return count * price;
}let and const are block-scoped: they exist inside the nearest { }. The older var is
function-scoped: it ignores blocks and is visible throughout the function. Prefer const,
use let when you must reassign, and avoid var.
A function remembers where it was born
When a function is created, it keeps a reference to the variables around it. That pairing of function and captured variables is a closure.
function makeCounter() {
let count = 0;
return () => {
count += 1;
return count;
};
}
const next = makeCounter();
next(); // 1
next(); // 2makeCounter has returned, yet count lives on: the arrow function still references it. Each call
to makeCounter() creates a fresh count, so two counters never interfere.
Private state without classes
Nothing outside can read or change count directly. That makes closures a lightweight way to hide
state:
function createWallet(start) {
let balance = start;
return {
pay(amount) {
if (amount > balance) throw new Error("Insufficient funds");
balance -= amount;
},
get balance() {
return balance;
},
};
}The classic loop bug
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0); // 3, 3, 3
}
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0); // 0, 1, 2
}With var there is one i for the whole loop; by the time the callbacks run, it's 3. With let,
each iteration gets its own binding, captured by its own callback.
Memoisation: closures as caches
A closure can hold a cache that survives between calls:
function memoise(fn) {
const cache = new Map();
return (n) => {
if (!cache.has(n)) cache.set(n, fn(n));
return cache.get(n);
};
}
const slowSquare = (n) => n * n;
const fastSquare = memoise(slowSquare);The cache lives as long as fastSquare does. That's also the warning: a closure keeps everything
it captured alive, so an ever-growing cache is a memory leak.
Common mistakes
- Capturing a variable you later reassign: the closure sees the new value, not the one at creation time.
- Accidentally keeping large objects alive: an event listener that captures a big array keeps it in memory until the listener is removed.
- Using
varin loops that create callbacks.
Closures and scope are core material in JavaScript Intermediate.
Questions and answers
- What is a closure in JavaScript, in one sentence?
- A closure is a function together with the variables it captured from the place where it was created, which it can keep reading and updating after that outer function has returned.
- Why does a for loop with var print the same number every time?
- var is function-scoped, so all the callbacks share one variable, which holds its final value by the time they run. let creates a new binding for each iteration, so each callback sees its own value.
Practise it
Read next
- JavaScript promises and async/await: a practical guide
How promises work, what await really waits for, running tasks in parallel with Promise.all, handling errors properly, and the event loop in two minutes.
- JavaScript equality and type coercion: == vs ===, truthy and falsy
Why 0 == '' is true, which values are falsy, how + turns numbers into strings, and the handful of rules that make JavaScript comparisons predictable.