In the last video, makeTeamScorer() handed back a scorer that kept adding to its own total, even after makeTeamScorer() itself had returned. Two teams got two scorers, and their totals never mixed. A function that remembers the variables from where it was created is a closure.
Now you’ll write functions like that yourself. You’ll build functions that come preset with a setting and scorers that hand you more than one function. Then you’ll predict what a closure sees when its variable changes later, especially inside a loop. Start with the smallest version: a function that makes scoring functions.
Hand a Function Its Settings
Marco’s rounds don’t all score the same way. A music answer earns one point, but the picture round has only five pictures, so each one earns two points to give the round a maximum of ten points. He could write a separate helper per round, but each would repeat the same multiplication with a different number.
Instead, one function can build each helper and bake the number in:
round_points.js
function makePointsFor(pointsPerAnswer) {
return (correct) => correct * pointsPerAnswer;
}
const musicPoints = makePointsFor(1);
const picturePoints = makePointsFor(2);
console.log(`Music, 7 right: ${musicPoints(7)}`);
console.log(`Pictures, 4 right: ${picturePoints(4)}`);
Each helper uses the setting it was made with:
$ node round_points.js
Music, 7 right: 7
Pictures, 4 right: 8
A function that builds and returns new functions is called a factory function. Every call to makePointsFor() creates a new pointsPerAnswer variable, and the arrow returned from that call links to it.
So musicPoints reads a pointsPerAnswer of 1, and picturePoints reads a separate one holding 2. The factory has long finished by the time you call either helper, but each closure still reaches the variable from its own call.
If you’d like to try one before moving on, the button opens a chat where the mentor suggests a scoring rule for you to turn into a factory.