In Make a Function That Remembers, each scaler kept its own factor in the box of the call that made it. A factor never changes after that call, though. Sam needs a number that does change. While a recipe is on the stove, the recipe box should keep track of how many of its steps are done, and that number goes up as Sam cooks.
In this lesson, you’ll write functions that change what their closure keeps. You’ll also predict what each later call sees. You’ll build a step tracker whose count only its own functions can change, ready for the recipe box. Start with the smallest piece, a single function that counts.
Change What a Closure Keeps
A step counter has to remember a number between calls and change it each time. A closure can do both. Open a new tab at about:blank, open the Console, and make a counter for Grandma Ines’s lentil soup, which has two steps: softening the onions and simmering. Then finish its steps one call at a time, including one call more than the soup has steps:
> function makeStepCounter(total) {
… let done = 0;
… return () => {
… done += 1;
… return `Steps done: ${done} of ${total}`;
… };
… }
undefined
> const finishSoupStep = makeStepCounter(2);
undefined
> finishSoupStep()
'Steps done: 1 of 2'
> finishSoupStep()
'Steps done: 2 of 2'
> finishSoupStep()
'Steps done: 3 of 2'
The same call, finishSoupStep(), returned a different string each time, so something changed in between. That something is done. The arrow doesn’t declare done, so its walk goes one box out, to the box of the makeStepCounter(2) call, as a scaler’s walk does for factor.
This time, done += 1 changes the variable in that box. The second call walks to the same box, finds 1 there, and adds one more. That’s why done is declared with let.
So a closure keeps the variable itself, not a copy of its value. The arrow was made when done was 0, but it never stored that 0. Each call reads done as it is at that moment, including changes an earlier call made. A function like makeStepCounter(), which makes and returns new functions, is often called a factory function, or a factory.