In this video, you answered the egg timer’s question and saw how a function made inside another one still has what it needs after that other function has finished.
Key Points
- A call that’s over can leave its box behind. Each call of a function makes a box for its parameters and variables. Usually, once the call is over, nothing links to that box. Your code can never reach it again, and JavaScript clears it away.
- A function made inside a call links to that call’s box. If the call returns that function, or hands it to
setTimeout(), the link keeps the box alive, and the function can still read the box’s variables whenever it runs. - A call’s variables don’t become top-level names. Typing
factorat the top level gives aReferenceError, because a walk from the top level never looks inside a function’s box. Only a function made inside the box can reach them, by walking one box out. - Every call makes a new box. Where a function is written decides what its box holds and which boxes surround it, and each call makes a fresh box of that shape. Calling
makeScaler()twice made two boxes, each with its ownfactor, and each returned arrow links to the box of the call that made it. Making the second scaler didn’t change the first. - A function together with the box it keeps is called a closure. The egg timer’s arrow is one too. Each call of
startEggTimer()makes its own box, so each timer logs its own pan.
The Code
Open a new tab at about:blank, open the Console, and type these entries. A scaler for Grandma Ines’s lentil soup, which serves six and uses 200 grams of lentils: