Closures:- Since a nested function is a closure, this means that a nested function can “inherit” the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function. The closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining. (The reason it is called “chaining” is explained later+). Closures provide encapsulation for the variables of the inner functions.
Consider the following example:
function A(x) {
function B(y) {
function C(z) {
console.log(x + y + z);
}
C(3);
}
B(2);
}
A(1); // Logs 6 (which is 1 + 2 + 3)
In this example, C accesses B‘s y and A‘s x.
This can be done because:
Bforms a closure includingA(i.e.,Bcan accessA‘s arguments and variables).Cforms a closure includingB.- Because
C‘s closure includesBandB‘s closure includesA, thenC‘s closure also includesA. This meansCcan access bothBandA‘s arguments and variables. In other words,Cchains the scopes ofBandA, in that order.
The reverse, however, is not true. A cannot access C, because A cannot access any argument or variable of B, which C is a variable of. Thus, C remains private to only B