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:
B
forms a closure includingA
(i.e.,B
can accessA
‘s arguments and variables).C
forms a closure includingB
.- Because
C
‘s closure includesB
andB
‘s closure includesA
, thenC
‘s closure also includesA
. This meansC
can access bothB
andA
‘s arguments and variables. In other words,C
chains the scopes ofB
andA
, 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