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

Nested Functions

Inside a function you can define and use other functions. Here's an example that shows a helper function to simplify a complicated calculation.

In the definition of a function you can refer to the arguments of the function. You can also refer to variables outside the function in the enclosing function. Here's the same example but with a constant 1 factored out as a variable.

That was actually the first example of a closure! The outer function closes over the inner functions, and the inner functions can use variables from the outer function.

An important case is when the inner function refers to arguments from the enclosing outer function. Arguments are like variables, you can refer to them from inside in the same way.

Here is an example of a function create that takes an argument x and returns a new function. The returned function takes no arguments and returns x.

In the example above, even after the create function finishes the function it returns keeps working. That's the magic of closures, the reference to x in the outer scope is still valid even after the outer function finishes. Deep, man.

So what is a closure? A closure is a function plus enclosing environment. In JavaScript when you're passing around function values, you're passing around closures!

Define a function named genesis that takes two arguments x and y. It should return a function that always returns x + y.


about news main