Javascript Placement Series (Part : 5) Discussing about Closure and important interview Question ?
Table of contents
About Closure ?
In Javascript, one of the most important and theoretical topic is Closure. It is one of the most misunderstood topic.
What is closure ?
Closure is nothing but combination of function bundled together with the references to its surrounding state. In simple terms closure gives you the access to an outer function's scope from an inner function.
Let us take couple of examples to understand it properly.
You would really be surprised if I tell you that the above code which you just saw is closure. Yes, Closure means that its an ability that a function can access variables from its outer function that is what function y( ) is doing. It is accessing variable a from its outer function x( ).
Now let me show you one cool thing about closure. Let me ask you a question.
What would be the output of the above code ? Will there be an error or something else. Let me show you the output.
Lets understand what happened here .
When you returned the function y( ), not just the code was returned rather closure was returned which means function along with reference to its surrounding (lexical scope) is returned. And hence when you execute multiple lines and then try to run the returned function you get the value of a. Even though variable a was executed way before.
Few Important concept questions ?
Lets try guessing output of this code
We all know that when a function is returned it is returned as a closure, which means it will have the function and also the reference to the surrounding state. That means it will have the reference to a and whatever value of a is it will console that value.
Lets think a moment and we have already understood that closure holds function and reference of the outer state but to can it go a level up.
Look into the following code.
Try guessing the answer
Yes, you guessed it write, the closure can hold the value reference to more levels. That means the surrounding state can be of any level.
Uses of Closure
Module design pattern
Currying
Functions like once
Memoize