According to wikipedia, a closure is:
a technique for implementing lexically scoped name binding in languages with first-class functions.
I don't think this mouthful definition is comprehensible to anybody learning the language. So I decide to break it down and explain it in plain language.
Lexical scope = static scope, it refers to
An example to illustrate this concept:
We can determine where foo and bar can be accessed within the program by looking at the code. Thus, the scopes of the variables are determined statically.
To contrast it with dynamic scope:
The value of x is not determined until runtime. Thus,
console.log(x) has no idea what will be printed out. Also, x is neither a globally variable nor is defined within the
log function. But
log has access to it.
So now we understand what the fancy term lexical scope means, let's take a look at the definition of first-class function
A language supports:
- passing functions as arguments to other functions
- returning them as the values from other functions
- assigning them to variables
- storing them in data structures.
This one is easy to understand:
According to this explanation,
Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created.
Highlights of this example:
inner()has access to variable x, which is defined outside of it
var test = outer()is equivalent of
var test = inner()but test has no access to
- The value of
xis stored in memory so that any subsequent call of
test()will print 5
So to summarize what a closure is:
- A function f that is nested within another function
- f accesses variables defined in the outer function
During the research of closure, another term comes up often:
A function that does at least one of the following:
- takes one or more functions as an input
- outputs a function