JavaScript/Closures

A Closure is a technique where a function is bundled (enclosed) with its surrounding variables, the lexical environment. Typically, Closures are implemented in functional programming languages like JavaScript where they support Currying.

Lexical environment
First, we show the access of a function to its lexical environment. This alone is not a Closure.

The function  increments its parameter by the value of the variable. Because  as well as   are defined within the same block, the function has access to the variable. Whenever the function is called, it reads the variable and uses it to compute its return value.

Closure
To extend the above example to a Closure, we have to combine an (inner) function with access to variables of its lexical environment - typically another function -, and save this state by returning this inner function.

The (outer) function
 * contains a parameter ,
 * defines an (inner) function  that takes another parameter  ,
 * in addition to its parameter, the (inner) function has access - as usual - to its lexical environment where  is defined
 * returns the (inner) function.

So far, there are exclusively declarations and no running code.

When the variable  is declared in line 12, it is initialized with the return value of the function. This is the crucial point where code runs and the Closure technique acts. Within  the 5 is known as the parameter/variable. Next, the function  is created using   from its lexical environment. This function  accepts one parameter that must be given from the calling routine later on. The return statement of  delivers this function   that has bound the value '5' into its body. Please note that the function name  is arbitrary and not seen outside of.

When  is called a second time with the argument '6', the '6' is bound to a separate, second function.

Exercises

 * ... are available on another page (click here).