Hello Readers,
- Keep Reading this Blog to know more about Closures ....
- Lets Look at this Example:
1. function x(){
2. var a=14;
3. function y(){
4. console.log(a);
5. }
6. y();
7. }
8. x();
- The above is a Example for Closure. We already know the output of this program ie a equals 14, but lets understand theory behind this.
- First we need to Understand what Lexical Scoping(LS) means,
- LS means when y() gets called, it tries to find a variable inside local memory but a is not found, so it goes to its Lexical Parent and it finds variable a and thus console logs it. This is called Lexical Scoping.
- A Function bundled together with its Lexical Environment forms Closure. Here the Function y was bundled to variables of x.
- so in One Way, This is what Closure is !!!!
Closure Deep Dive
- Consider the Example:
1. function x(){
2. var a=14;
3. function y(){
4. console.log(a);
5. }
6. return y;
7. }
8. var z=x();
9. z();
- what is the output of the above program?
- The answer is when z() called in line9 returns 14, But how is that possible????
- We Know that JS is Synchronus ie after running line 8, x is Deleted ie X() Execution Context(EC) gets Deleted in Call Stack.
- To know more about EC, Read my EC Blog
- In the above Example, 'a' is not in Global Scope and x gets deleted after line 8, So how program console logs 14. Here Closure comes into picture.
- When Functions are Returned from Another Function, They still maintain their Lexical Scoping.
- When y is returned, not just function code gets returned but Closure enclosed function along with its Lexical Environment gets returned and was assigned to z. This is the use case of Closures.
- Other Uses of Closures:
- Currying
- setTimeout
- memoize etc
- Thanks for Reading my Blog folks, Have a great Day :)
Top comments (15)
Short and clear blog buddy!👏
Thank you :)
Thanks for the article. I have a question though. Why was the function returned when
y
instead ofy()
was called?Because I wanted to return the function y and not to invoke or call it .
y-->returning function y.
y()--> Invoking or calling the function.
Thank you. I understand better now
Glad you liked it :)
Nice and concise 👍
Thank you :)
Good Information thanks
Glad you Liked it :)
Nice Information.
Ty and Have a Great Day :)
Clearest impossible!
Thanks,it helps me a lot. Can I translate it into Chinese and share it to more people on juejin.im ?
ok