In this lesson, you watched Marco’s makeTeamScorer() make a scorer for the Know-It-Owls that keeps adding to its own total after makeTeamScorer() has returned, and a second scorer for Table Six with a total of its own.
Key Points
makeTeamScorer()takes a team name, setstotalto0, and returns an arrow function without calling it. The arrow doesn’t declaretotalorteamName. Walking outward from where it’s written, you find both one box out, inmakeTeamScorer().- Calling
makeTeamScorer("Know-It-Owls")puts a frame on the call stack, and with it a box for that call’s variables. It’s the box around the function’s code, filled in for this one call. When the call returns, its frame comes off, but the box stays where it is. The arrow it made links to that box, so JavaScript keeps it. - Watch out: a function’s variables aren’t wiped out when it returns. They last as long as something can still reach them.
- Each time you call
scoreOwls(), the arrow’s frame goes on the stack with its ownpoints. The walk fortotalandteamNamesteps one box out, along its link, to the Know-It-Owls call’s box. The first call takestotalfrom0to7, and the second finds the sametotal, still at7, and adds9. - When a
scoreOwls()call returns, itspointsgoes with its frame, because nothing links to it. Every call you’ve followed on the stack worked that way.totalstays, because the arrow still links to its box. - A function together with the variables it links to from where it was made is called a closure. That’s how
scoreOwls()keeps the Know-It-Owls’ total from one call to the next. - Every call of
makeTeamScorer()runs its body again, solet total = 0;makes a newtotalbeside a newteamName. The arrow that call returns links to those. - Watch out: the two scorers don’t share one total. Each
totalbelongs to one call ofmakeTeamScorer(), not to the function itself. - The rule is that a function made inside a call keeps that call’s variables, even after the call returns. Each call makes new variables, so each scorer keeps a total of its own.
Final Code
Here’s scorers.js, with a scorer for each of the two teams: