Closures are functions that refer to independent (free) variables.
In short, variables from the parent function of the closure remain bound from the parent's scope.
Consider the following:
function init() {
var name = "Mozilla"; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert (name); // displayName() uses variable declared in the parent function
}
displayName();
}
init();
init() creates a local variable name and then a function called displayName(). displayName() is the inner function (a closure) — it is defined insideinit(), and only available within the body of that function . Unlike init(), displayName() has no local variables of its own, and instead reuses the variable name declared in the parent function.
Run the code and see that this works. This is an example of lexical scoping: in JavaScript, the scope of a variable is defined by its location within the source code (it is apparent lexically) and nested functions have access to variables declared in their outer scope.