what is closure ?

what is closure ?

Table of contents

No heading

No headings in the article.

Definition of the closure :

When the function is executed out of it's lexical scope(means where it was physically declared in the block of code) then this function will get reference to it's lexical variable environment as a persistent storage is called as closure. In the other words this function will still be access to surrounded data when executed out of it's scope.

Persistent means the value for the variable will remains stored between the function calls.

Other name for the closures are Persistent Lexical Scoped Referenced Data(PLSRD) and Closed Over Variable Environment (COVE)

This is bit complex to understand but let's take one example to understand it better.

closure_final.png

Notice that we have created Function inner inside outer function and we are returning it and storing it in a new label called incrementCounter. so we are executing the inner function out of it's scope. so this is why its forms a closure.

In General when we invoke function outer it's execution context will be created and variable counter and inner function will get the local memory and once we return from the outer it's execution context will be destroyed.

But here we are returning a function which is using the variables declared inside the outer function. So the returned function will carry references to all the variables which is used inside it. This returned function has still the reference to it's surrounding variable environment. These data will be persistent across the function calls.

Here incrementCounter will get reference to the person and counter variable.

As we can see that the returned function is stored inside the incrementCounter label. So when we invoke the incrementCounter function, its execution context will be created and it will look for counter inside it's local memory but it will not find then it will go to it's persistent storage and it will find it there and increment counter by 1.

on the second call of incrementCounter function the counter value is 1 (persisted between function calls) and it will increment by 1 so it will become 2 and on next invocation it will become 3.

This persistence data is stored inside the private property called [[scope]].

Notice that we can not access this property to modify the data as this property is private and we can change this persisted data only through calling the incrementCounter function. There is no other way to change the persisted data other than calling incrementCounter function.

Thanks for reading this blog.

comments down if you have any query.