[sign in]

What's a Closure?

  1. What's a Closure?
  2. Variables and Values
  3. Defining Functions
  4. Side Effects
  5. Functions are Values
  6. Returning Functions
  7. Function Scope
  8. Nested Functions
  9. Stateful Closures
  10. Private Data
  11. Asynchronous Callbacks
  12. Continuation Passing

Stateful Closures

A useful thing that closures can do is keep track of internal state. Remember that a closure is created when an inner function refers to an outer function's variables. So far we've just been reading the values, but we can write to them as well.

Here's an example of a function that creates a counter.

Where is the state kept? It's in the variable count in the outer scope. Why are there two copies? Each invocation of makeCounter creates a new scope for count, and the closure surrounding the inner function f captures that scope.

Define a function named makeAccumulator that takes no arguments. It should create and return a function that takes one argument and returns a running total of all the arguments it has seen. E.g if f is the function returned by makeAccumulator, the first time you call f(3) it should return 3, then if you call f(2) is should return 5.

1:1

about news main