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 innerFunc()
and outerFunc()
is pop out from callstack means all variables present inside outerFunc()
is get garbage collected. but if now we call innerFunc()
a.k.a closureDemo()
it will print value of outerVar (which is member of outerFunc()). when running above code, you will see below output.
Outer Variable
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
.
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
console.dir(clouserDemo);
after running the code, you will see below output in console.
Key Notes
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
Top comments (0)