O'Reilly logo
  • Ahmed Elgendy thinks this is interesting:

Looking behind the curtain...

Let’s step through the code to see how the counter works.

  1. We call makeCounter, which creates a counter function and returns it along with an environment containing the free variable, count. In other words, it creates a closure. The function returned from makeCounter is stored in doCount.

  2. We call the function doCount. This executes the body of the counter function.

  3. When we encounter the variable count, we look it up in the environment, and retrieve its value. We increment count, save th...


Cover of Head First JavaScript Programming


How does the closure work via returning a function from a function?