Closures
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Closures: A Function That Remembers
Look closely at the code below: `makeGreeter(name)` creates an inner function `greet` and returns that inner function. Normally, local variables disappear as soon as a function finishes. Yet even after `makeGreeter("Zap")` has finished running, calling the returned `greetZap()` function still remembers that `name` is `"Zap"`:
function makeGreeter(name) {
function greet() {
console.log("Hello " + name + "!");
}
return greet;
}
const greetZap = makeGreeter("Zap");
greetZap();
greetZap();How is that possible? Whenever an inner function is created, it packs a ”backpack” containing the variables from its surrounding scope (`name`). Even after the outer function finishes, the inner function keeps that backpack with it. A function together with the outer variables it remembers is called a closure!
Exercise 2 — Each Closure Has Its Own Memory
Every time you call `makeGreeter()`, JavaScript creates a separate closure with its own independent memory. So if you create `greetZap` and `greetAqua`, each function remembers its own `name` without interfering with the other:
function makeGreeter(name) {
return function () {
console.log("Hello " + name + "!");
};
}
const greetZap = makeGreeter("Zap");
const greetAqua = makeGreeter("Aquachu");
greetZap();
greetAqua();
greetZap();`greetZap` permanently remembers `"Zap"`, and `greetAqua` permanently remembers `"Aquachu"`. Notice also the shorter syntax `return function () { ... }`, which returns the inner function directly!
Exercise 3 — Updating a Remembered Variable
A closure doesn't just read remembered variables—it can update them too! Look at `makeCounter()` below: it declares `let count = 0` and returns an inner function that adds `1` to `count` each time it is called:
function makeCounter() {
let count = 0;
return function () {
count = count + 1;
return count;
};
}
const nextTurn = makeCounter();
console.log(nextTurn());
console.log(nextTurn());
console.log(nextTurn());Every time `nextTurn()` is called, it updates the exact same `count` variable (`1`, `2`, `3`)—and because `count` lives inside `makeCounter`, no outside code can accidentally reset or mess with it! Plus, if you call `makeCounter()` a second time, you get a second counter with its own separate `count`:
function makeCounter() {
let count = 0;
return function () {
count = count + 1;
return count;
};
}
const counterA = makeCounter();
const counterB = makeCounter();
console.log(counterA());
console.log(counterA());
console.log(counterB());Exercise 4 — Quiz: Still Remembered
What does this code print?
function make(x) {
return function () {
return x * 2;
};
}
const double = make(5);
console.log(double());105undefinedHint : The returned function kept a link to the value it was built with.
Exercise 5 — Quiz: The Counter
What does this code print?
function makeCounter() {
let n = 0;
return function () {
n++;
return n;
};
}
const next = makeCounter();
next();
next();
console.log(next());3120Hint : The remembered variable is not rebuilt at each call.
Exercise 6 — Quiz: Two Independent Counters
What does this code print?
function makeCounter() {
let n = 0;
return function () {
n++;
return n;
};
}
const a = makeCounter();
const b = makeCounter();
a();
a();
console.log(b());1320Hint : Each call to the factory builds its own separate memory.
Exercise 7 — Build a Greeter
Complete the factory so the returned function remembers the name.
Hint : The factory must hand the inner function back, and that function uses the parameter itself.
Exercise 8 — A Counter That Remembers
Complete the counter so it keeps growing between calls.
Hint : The remembered value must be allowed to change, and the inner function works on that same one.
Exercise 9 — Closure Cheat Sheet
Match each element with its description.
Exercise 10 — Quiz: Why It Works
Why can the returned function still read `name` after the outer function ended?
Hint : Think about what a function carries with it from the moment it is built.
Exercise 11 — Codémon Factory
Build a factory that creates independent battle counters, one per Codémon, each remembering its own state.
Step 1: `makeFighter(name)` declares a local `wins` worth 0, then returns a function. Step 2: the returned function increases `wins` by 1 and returns `"name has N win(s)"`. Step 3: build a fighter for Zap and one for Aquachu. Step 4: make Zap win twice, Aquachu once, then Zap once more, printing each result. The two counts must never mix.
Expected output:
Zap has 1 win(s)
Zap has 2 win(s)
Aquachu has 1 win(s)
Zap has 3 win(s)// Write your factory here
// Use it here