Closures as state in JavaScript
A function that outlives its scope keeps the variables it used.
function makeCounter(start = 0) {
let count = start;
return {
increment: () => (count += 1),
reset: () => (count = start),
get value() {
return count;
},
};
}
const a = makeCounter();
const b = makeCounter(10);
a.increment();
a.increment();
b.increment();
console.log(a.value, b.value);
a.reset();
console.log(a.value, Object.keys(a));
How it works
- Each call to the factory creates fresh state.
- Returning several functions shares one private scope.
- This is how JavaScript did private fields before #.
Keywords and builtins used here
Objectconstfunctionletreturn
The run, in numbers
- Lines
- 20
- Characters to type
- 337
- Tokens
- 118
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 71 seconds.
Step 1 of 4 in Closures, step 1 of 16 in Functions & patterns.