Create a counter with a closure in JavaScript
Intermediate · 4 min read
A counter is the classic first example of a closure, one of the ideas that makes JavaScript click. You will build a function that hands back a little counter: tick() adds one, value() reads the count. Nobody else can touch the number. Ticket machines, click counters, id generators and rate limiters all use this pattern to keep state private.
In this tutorial you will write makeCounter, check that two counters keep separate counts, and then see the most famous closure bug of all: functions made inside a var loop all remembering the same number. You need to know how to write functions, including arrow functions, and how a for loop works.
Variables live in scopes
A variable declared inside a function with let or const belongs to that function's scope. Code outside can't see it. Normally, when a function finishes, its variables are thrown away.
A closure keeps them alive
If a function creates another function and returns it, the inner function still remembers the outer function's variables, even after the outer one has finished. That memory is a closure. The variable lives on because something still refers to it.
function makeGreeter(name) {
return () => 'Hello, ' + name;
}
const greetBola = makeGreeter('Bola');
console.log(greetBola()); // Hello, Bola
makeGreeter finished long ago, but greetBola still knows name.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
95 A counter that keeps its own count
fairWrite a function that returns a counter: a tick that increases a private number and a value that reads it. Two counters must not share a count. Then look at what var does to a function made inside a loop.
Stuck? Three hints, smallest first
- 1. Declare the count inside the maker, and return functions that refer to it.
- 2. Each call to the maker creates a new variable, so each counter is independent.
- 3.
varin a loop header is one variable for the whole loop;letis one per turn.
Step 1: a counter maker
function makeCounter(start = 0) {
let count = start;
return {
tick: () => ++count,
value: () => count,
};
}
const gate = makeCounter();
gate.tick();
console.log(gate.tick()); // 2
console.log(gate.value()); // 2
count is declared inside makeCounter. The two arrows in the returned object both refer to it, so it stays alive. ++count adds one and then gives the new value, which is why the second tick returns 2. (count++ would give the old value, 1.)
Step 2: two counters, two counts
Each call to makeCounter runs the function again, and creates a brand new count:
function makeCounter(start = 0) {
let count = start;
return {
tick: () => ++count,
value: () => count,
};
}
const gate = makeCounter();
const kiosk = makeCounter(10);
gate.tick();
gate.tick();
kiosk.tick();
console.log(gate.value()); // 2
console.log(kiosk.value()); // 11
The gate and the kiosk can't interfere. Each has its own private number.
Step 3: really private
Try to reach the count from outside:
function makeCounter(start = 0) {
let count = start;
return {
tick: () => ++count,
value: () => count,
};
}
const gate = makeCounter();
console.log(gate.count); // undefined
gate.count = 99;
console.log(gate.value()); // 0
count is not a property of the object. It's a variable inside makeCounter, and the only way to it is through tick and value. Setting gate.count = 99 just adds an unrelated property. The real count is safe.
Step 4: the var loop bug
Now the wrong turn. Make three functions in a loop, each meant to remember its own number:
const varFns = [];
for (var i = 0; i < 3; i++) varFns.push(() => i);
console.log(varFns.map((f) => f())); // [ 3, 3, 3 ]
You might expect [0, 1, 2]. But var makes one variable i for the whole loop, not one per turn. All three arrows close over that same i. By the time you call them, the loop has finished and left i at 3. So they all say 3.
This bites in real code when a loop sets up click handlers or timers: every handler sees the last value.
Step 5: let fixes it
const letFns = [];
for (let j = 0; j < 3; j++) letFns.push(() => j);
console.log(letFns.map((f) => f())); // [ 0, 1, 2 ]
let in a loop head creates a fresh variable for each turn. Each arrow closes over its own j, which keeps the value it had on that turn.
Step 6: a ticket machine in one go
You don't always need a named maker. You can define a function and call it at once, by wrapping it in brackets and adding () at the end:
const nextTicket = (() => {
let issued = 0;
return () => 'T' + String(++issued).padStart(3, '0');
})();
console.log(nextTicket()); // T001
console.log(nextTicket()); // T002
console.log(nextTicket()); // T003
The outer arrow runs once and returns the inner one. issued is private to it. padStart(3, '0') adds leading zeros, so 1 becomes '001'. Before let existed, this "call it straight away" trick was how people gave each loop turn its own scope.
The full solution
The answer panel has makeCounter with two independent counters, the var and let loops side by side, and the ticket machine. Press Run to see the output.
function makeCounter(start = 0) {
let count = start; // private: only these two functions can see it
return {
tick: () => ++count,
value: () => count,
};
}
const gate = makeCounter();
const kiosk = makeCounter(10);
gate.tick();
const afterTwo = gate.tick();
kiosk.tick();
// var is function-scoped, so all three closures share one i, read after the loop.
const varFns = [];
for (var i = 0; i < 3; i++) varFns.push(() => i);
// let is scoped to the turn, so each closure has its own j.
const letFns = [];
for (let j = 0; j < 3; j++) letFns.push(() => j);
// The same idea as a ticket machine: state that nothing else can reach.
const nextTicket = (() => {
let issued = 0;
return () => 'T' + String(++issued).padStart(3, '0');
})();
console.log('gate:', gate.value(), 'kiosk:', kiosk.value());
console.log('var:', varFns.map((f) => f()), 'let:', letFns.map((f) => f()));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('two ticks', afterTwo, 2);
test('and the closure still remembers', gate.value(), 2);
test('a second counter has its own count', kiosk.value(), 11);
test('so the first is untouched', gate.value(), 2);
test('the variable itself is unreachable from outside', gate.count, undefined);
test('var in a loop leaves one shared binding, read after the loop ended', varFns.map((f) => f()), [3, 3, 3]);
test('let makes one binding per turn', letFns.map((f) => f()), [0, 1, 2]);
test('a ticket machine keeps its own numbering', [nextTicket(), nextTicket(), nextTicket()], ['T001', 'T002', 'T003']);
count outlives makeCounter because the returned functions still refer to it — that is a closure, and it is the plainest way to have private state in JavaScript. gate.count is undefined not because it is hidden but because it is not a property of anything; there is no path to it except through tick and value. Each call to the maker creates a new one, which is why the two counters cannot interfere.
var giving [3, 3, 3] is the interview question and a real bug in any loop that registers handlers. There is one i for the whole function, all three arrows close over it, and by the time they run the loop has finished and left it at 3. let creates a fresh binding per iteration, so each arrow captures its own. Before let, the fix was an immediately-invoked function per turn to make a new scope by hand — the same trick nextTicket uses here, for the same reason.
Common mistakes
- Declaring the count outside the maker. Then every counter shares one number.
- Using
varin a loop that creates functions. They all see the final value. Uselet. - Mixing up
++countandcount++. The first gives the new value, the second the old one.
Try it yourself
- Add a
reset()function to the counter that puts the count back tostart. - Give
makeCounterastepparameter somakeCounter(0, 5)counts 5, 10, 15. - Write
makeLimiter(max)that returns a function which givestruethe firstmaxtimes it is called, thenfalse.