Most of us, as soon as they read/hear the name of closure. either immediately skip the topic or find it very difficult to understand the concept. In this post I will try my best to simplify the concept of closure.
before coming to definition, look at the below code snippets.
When the above code is executed, then first
outerFunc() get into callstack.
outerFunc() will return
outerFunc() is pop out from callstack means all variables present inside
outerFunc() is get garbage collected. but if now we call
closureDemo() it will print value of outerVar (which is member of outerFunc()). when running above code, you will see below output.
But how it's possible?
outerVar which is defined inside
outerFunc(). and now
outerFunc() is no longer available in callstack. but still
innerFunc() have access to variable
outerVar is declared with let and we know let variable are function scoped.
So, here comes the concept of closure.
The closure is a function that closes over ( a.k.a. capture, remembers) the variables from it's lexical scope.
so even after executing function from anywhere (even outside of it's lexical scope) it remembers the variables/function from the place where it's defined.
In above code, add the below line in last
after running the code, you will see below output in console.
If any variables/function from their lexical scope is referenced inside inner function. then only closure is created else closure will not created
Closure function will remember variable reference not value.
if we run above code it log
Changed Value in console
I am newbie in writing technical content, So may be this post will not clear your closure concepts. For more detailed explanation & information about closure, I would suggest you to please go through the articles mentioned in References