In JavaScript, a closure is a function that refers variables in the outer scope from its inner scope. The closure preserves the outer scope inside its inner scope.
To understand the closures, you need to know how the lexical scoping works. Please refer the below link.
SCOPE CHAIN AND LEXICAL ENVIRONMENT
The closure has three scope chains listed as follows:
Access to its own scope.
Access to the variables of the outer function.
Access to the global variables.
function OuterFunction() {
var outerVariable = 1;
function InnerFunction() {
alert(outerVariable);
}
InnerFunction();
}
In the above example, InnerFunction() can access outerVariable even if it will be executed separately. Consider the following example.
function OuterFunction() {
var outerVariable = 100;
function InnerFunction() {
alert(outerVariable);
}
return InnerFunction;
}
var innerFunc = OuterFunction();
innerFunc(); // 100
In the above example, return InnerFunction;
returns InnerFunction from OuterFunction when you call OuterFunction(). A variable innerFunc
reference the InnerFunction() only, not the OuterFunction(). So now, when you call innerFunc(), it can still access outerVariable
which is declared in OuterFunction(). This is called Closure.