After this lesson you can explain what a closure is in your own words and use one to build a counter, a private variable or a small factory function. Closures sound advanced, but you have probably already used them without noticing.
The idea in one example
Read this carefully:
function makeGreeter(greeting) {
return function (name) {
return greeting + ", " + name + "!";
};
}
const sayHello = makeGreeter("Hello");
console.log(sayHello("Asha")); // Hello, Asha!makeGreeter has finished running by the time we call sayHello. Normally a function's variables vanish when it ends. Yet the inner function still knows greeting. It carries that variable with it.
A closure is exactly this: a function plus the variables from the place where it was defined. Every function in JavaScript works this way. The behaviour only becomes visible when a function is used somewhere other than where it was created.
A counter with private state
Closures give you state that survives between calls:
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
function show(text) {
out.textContent += text + "\n";
}
function makeCounter() {
let count = 0;
return function () {
count = count + 1;
return count;
};
}
const counterA = makeCounter();
const counterB = makeCounter();
show("A: " + counterA());
show("A: " + counterA());
show("A: " + counterA());
show("B: " + counterB());
</script>You should see A count 1, 2, 3 and B start again at 1. Each call to makeCounter creates a fresh count, and the returned function keeps hold of its own. There is no way to read or set count from outside except through the function you were given. That is private state.
Returning several functions
You can return more than one function that share the same hidden variable:
function createWallet(start) {
let balance = start;
return {
deposit(amount) {
balance += amount;
return balance;
},
spend(amount) {
if (amount > balance) {
return "Not enough money";
}
balance -= amount;
return balance;
},
getBalance() {
return balance;
}
};
}
const wallet = createWallet(100);
console.log(wallet.deposit(50)); // 150
console.log(wallet.spend(500)); // Not enough money
console.log(wallet.spend(30)); // 120
console.log(wallet.balance); // undefinedwallet.balance is undefined: the variable is not a property, only a hidden local. The only way to change it is through the three methods, which protect the rule that you cannot spend more than you have.
Remembering a setting
A closure is also a neat way to create a configured version of a function:
function multiplier(factor) {
return number => number * factor;
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(7)); // 14
console.log(triple(7)); // 21double remembers factor as 2, and triple remembers 3. Same code, different remembered values.
Closures see variables, not copies
A closure holds on to the variable itself. If the variable changes later, the closure sees the new value:
let message = "first";
const read = () => message;
message = "second";
console.log(read()); // secondThis explains a famous bug. In a loop using var, there is only one i for the whole loop, so every callback sees its final value:
const callbacks = [];
for (var i = 0; i < 3; i++) {
callbacks.push(() => i);
}
console.log(callbacks.map(fn => fn())); // [ 3, 3, 3 ]Switch to let, which creates a new variable for each pass of the loop, and each callback keeps its own:
const callbacks = [];
for (let i = 0; i < 3; i++) {
callbacks.push(() => i);
}
console.log(callbacks.map(fn => fn())); // [ 0, 1, 2 ]This is one more reason to use let and const instead of var. See Scope for the underlying rules.
Where you will meet closures
- Event handlers. A click handler defined inside a function can use that function's variables later, when the click happens.
- Timers. A function passed to
setTimeoutremembers what it needs until it runs. - Callbacks such as the ones used with array methods, covered in Callbacks and functions as values.
- Modules and factory functions that hide internal details.
A memory note
Because a closure keeps its variables alive, they cannot be cleaned up while the function can still be called. For ordinary programs this is not a concern. It only matters if a closure holds a very large object that you no longer need; in that case, set the variable to null or stop referencing the function.
A closure inside an event-style callback
Here is a realistic use: a function that creates a handler which remembers a label. The same pattern is used when you attach click handlers to many buttons.
function makeLogger(label) {
let calls = 0;
return function (message) {
calls++;
console.log(label + " #" + calls + ": " + message);
};
}
const logInfo = makeLogger("info");
const logWarn = makeLogger("warn");
logInfo("started"); // info #1: started
logInfo("working"); // info #2: working
logWarn("slow"); // warn #1: slowEach logger has its own label and its own calls. Nothing outside can reset calls, so the numbering is reliable.
Common mistakes
Thinking each call shares state. Each call to the outer function creates a new set of variables. Two counters are independent.
Expecting a snapshot. Closures see the current value of a variable, not the value from when the function was created.
The var loop bug. Using var in a loop with callbacks gives the same final value to all of them. Use let.
Trying to read the private variable directly. wallet.balance is not there. Provide a function that returns it.
Over-engineering. Not every variable needs to be hidden. Use closures when you want private or remembered state, not by default.
Exercise
Write makeCounter(step) that returns a function that increases its count by step each call, so makeCounter(5) gives 5, 10, 15 and so on. Create two counters with different steps and show that they do not interfere. Then add a second returned function, reset, that sets the count back to 0. Hint: return an object with next and reset methods, like the wallet example.
Key points
- A closure is a function together with the variables from the place where it was created.
- The remembered variables stay alive for as long as the function can still be called.
- Closures let you keep private state that outside code cannot touch directly.
- Each call of the outer function creates a new, separate set of remembered variables.
- Closures remember variables themselves, not copies of their values, so later changes are visible.