JavaScript Closures
A closure is a function that keeps its surrounding variables. The inner function can use those variables after the outer function has finished.
A counter that remembers
makeCounter makes a counter. Each call adds one to the kept count.
function makeCounter() {
let count = 0;
return function () {
count = count + 1;
return count;
};
}
const counter = makeCounter();
console.log(counter());
console.log(counter());
console.log(counter());Two counters stay separate
Each counter gets its own kept count. One counter never changes the other.
function makeCounter() {
let count = 0;
return function () {
count = count + 1;
return count;
};
}
const counterA = makeCounter();
const counterB = makeCounter();
console.log(counterA());
console.log(counterB());
console.log(counterA());A function that adds a fixed amount
makeAdder keeps the amount it was given. The returned function adds that amount to any number.
function makeAdder(amount) {
return function (n) {
return n + amount;
};
}
const addFive = makeAdder(5);
console.log(addFive(10));
console.log(addFive(20));Example
function makeCounter() {
let count = 0;
return function () {
count = count + 1;
return count;
};
}
const first = makeCounter();
const second = makeCounter();
first();
first();
console.log(first());
console.log(second());Key points
- Closure: a function that keeps the variables from the scope where it was made
- The outer function runs once and returns the inner function.
- The inner function reads and changes the kept variables.
- Each call to the outer function makes a fresh set of kept variables.
- A closure keeps a variable alive after its scope would normally end.
In this example, makeCounter builds a counter function. The first counter runs three times and reaches 3. The second counter runs once and shows 1. Each counter keeps its own count.
Note
The kept variables stay private to the closure.
Try it Yourself
Edit the code, then press Run.
Runs in your browser β the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does a closure keep after its outer function returns?