Closures: functions that remember
A function keeps access to the scope where it was created — that is the whole idea, and it is powerful.
Every time a function runs, it gets a fresh scope. A closure is a function that keeps a reference to that scope after the outer function has returned. The variables stay alive because something still points at them.
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const next = makeCounter();
next(); // 1
next(); // 2
const other = makeCounter();
other(); // 1 — its own count, not sharedThat count is private. Nothing outside makeCounter can read or set it — only the returned function can. This is how you build state without classes or globals.
Three everyday uses
- Private state — the counter above, or a cache nobody else can touch.
- Factories —
const double = multiplyBy(2)produces a specialised function. - Run once / memoise — wrap a function so it only does the expensive work the first time.
function once(fn) {
let done = false;
let value;
return function (...args) {
if (!done) {
value = fn(...args);
done = true;
}
return value;
};
}Try it
Two counters, two states
Exercises
Checked in your browser · hints and solutions included
Exercise
Build a counter factory
Write makeCounter() that returns a function. Each call of that returned function returns 1, then 2, then 3, and so on. Two counters created from two calls must not share state.
Exercise
Run a function only once
Write once(fn) that returns a new function. The first call runs fn and returns its result. Every later call returns that same first result without running fn again.