Closures

Closures

lexical environment and closures

ยท

3 min read

Before we learn what closures are, we need to know what lexical scope is.

Lexical scope

Let us take the below program as an example:-

image.png

output:-

image.png

In the above example, we can see that even though the inner function does not have the declaration of the variable "name", yet it can access the variable and print its value. This is happening due to the lexical scope chaining.

The inner function at first looks up for the declaration of the variable, within its own local scope, and upon not finding it, it goes up to its immediate lexical parent's scope( i.e., outer function's scope ), in search of that variable, and this keeps going on until the variable is found, and this process is known as lexical scope chaining.

We can say that the variable "name" is within the lexical scope of the inner function.

lexical.png

So, now that we know what lexical scope is, let us move on to closures ๐Ÿ˜Ž.

Closures

Let us again take up a program as an example:-

image.png

output:-

image.png

In the above program, instead of executing the inner function, i.e., the function son, we are returning the function.

Now, we are catching the function son and executing it separately from the mother function, so basically we are committing the sin of separating a son from his mother. And by the time the function son gets invoked, the mother function is already out of the call stack of the js engine.

The purpose of the mother function was just to return the son function, which it did and as soon as it does, it gets out of the call stack.

So, the question arises that, if we are invoking the function son outside of the mother function and the mother function is already out of the call stack then from where the function son is getting the value for the variable "age"? Because according to lexical scope chaining, the function son will first look for that variable within its own local scope and upon not finding it, it will look up in the lexical parent's scope, but by that time, there will be no lexical parent.

So, the secret to the closures is that, in this kind of situations, when the inner function is dependent on its outer function's states/variables, the js engine automatically detects that, and in spite of the fact that the outer function goes out of the call stack, yet its variable objects remains in the memory of the inner function. The inner function remembers its lexical environment.

So, what actually closures does is that it bundles the inner function( i.e., son function ) with its lexical environment's states.

closures.png

Now, instead of just returning the inner function, the lexical environment states are also sent along, bundled together as a closure.

[ NOTE: closures does not store the value of the variables, but instead stores the reference to those variables. ]

ย