Get a Quote Right Now

Edit Template

Closures

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:

  1. B forms a closure including A (i.e., B can access A‘s arguments and variables).
  2. C forms a closure including B.
  3. Because C‘s closure includes B and B‘s closure includes A, then C‘s closure also includes A. This means C can access both B and A‘s arguments and variables. In other words, C chains the scopes of B and Ain 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

Share

Leave a Reply

Your email address will not be published. Required fields are marked *