JavaScript Closures
A closure is a function together with the variables it "remembers" from the place where it was created. Even after the outer function has finished running, an inner function can still read and update the outer function's variables. Closures are behind private state, factories, event handlers, memoisation and much more — you've probably used them already without knowing.
A first closure
function makeGreeter(greeting) {
return function (name) {
return `${greeting}, ${name}!`; // uses greeting from the outer function
};
}
const hello = makeGreeter("Hello");
const hola = makeGreeter("Hola");
console.log(hello("Ana"));
console.log(hola("Ana"));Hello, Ana!
Hola, Ana!
When makeGreeter("Hello") returns, its local variable greeting would normally disappear. But the returned function still refers to it, so JavaScript keeps it alive. Each call to makeGreeter creates a separate greeting, which is why hello and hola behave differently.
Private state: a counter
Closures can keep mutable state that nothing else can touch:
function createCounter(start = 0) {
let count = start; // private: only the functions below can see it
return {
increment: () => ++count,
decrement: () => --count,
value: () => count,
};
}
const clicks = createCounter();
const lives = createCounter(3);
clicks.increment();
clicks.increment();
lives.decrement();
console.log(clicks.value(), lives.value());
console.log(clicks.count); // not accessible from outside2 2
undefined
There's no way to set count to a nonsense value from outside — the only access is through the functions you chose to expose. This is the classic module pattern, used long before JavaScript had classes or #private fields.
Function factories
Closures make it easy to generate specialised functions from a general one:
const multiplier = (factor) => (n) => n * factor;
const double = multiplier(2);
const triple = multiplier(3);
console.log([1, 2, 3].map(double), [1, 2, 3].map(triple));
function makeValidator(min, max) {
return (value) => value >= min && value <= max;
}
const isPercent = makeValidator(0, 100);
const isAdultAge = makeValidator(18, 130);
console.log(isPercent(42), isPercent(140), isAdultAge(17));[ 2, 4, 6 ] [ 3, 6, 9 ]
true false false
Memoisation
A closure can hold a cache that survives between calls. Here a slow function gets a remembered result for each input it has seen:
function memoize(fn) {
const cache = new Map();
return (n) => {
if (cache.has(n)) {
console.log(` cache hit for ${n}`);
return cache.get(n);
}
const result = fn(n);
cache.set(n, result);
return result;
};
}
const slowSquare = (n) => {
console.log(` computing ${n}²`);
return n * n;
};
const fastSquare = memoize(slowSquare);
console.log(fastSquare(9));
console.log(fastSquare(9));
console.log(fastSquare(4)); computing 9²
81
cache hit for 9
81
computing 4²
16
Closures capture variables, not values
A closure keeps a reference to the variable itself, so it sees later changes. That's why the loop example below behaves differently with var (one shared variable) and let (a new variable for every iteration):
const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);
console.log(withVar.map((f) => f()));
console.log(withLet.map((f) => f()));
let mood = "happy";
const report = () => `I am ${mood}`;
mood = "sleepy";
console.log(report()); // sees the current value[ 3, 3, 3 ]
[ 0, 1, 2 ]
I am sleepy
Closures in everyday code
You use closures every time a callback refers to a variable from outside:
<button id="like">👍 0</button>
<script>
function setupLikeButton(button) {
let likes = 0; // remembered by the click handler
button.addEventListener("click", () => {
likes++;
button.textContent = `👍 ${likes}`;
});
}
setupLikeButton(document.getElementById("like"));
</script>Note: Variables held by a closure stay in memory as long as the closure itself is reachable. That's usually exactly what you want — but long-lived closures (e.g. listeners you never remove) holding large data can cause memory leaks.
Test yourself
What is a closure?
- A function that closes the browser window
- A function bundled with the variables of the scope where it was created
- A function with no parameters
- A way to end a loop
Given const add = a => b => a + b;, what is add(2)(5)?
- 2
- 5
- 7
- A function
Two counters created by separate calls to createCounter()…
- share one count
- each have their own count
- can't both exist
- share count only if declared with var