Javascript Placement Series (Part : 5) Discussing about Closure and important interview Question ?

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.

Screenshot (123).png

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.

Screenshot (124).png

What would be the output of the above code ? Will there be an error or something else. Let me show you the output.

Screenshot (124) (1).png 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 ?

Screenshot (126).png

Lets try guessing output of this code

Screenshot (126) (1).png

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.

Screenshot (127).png

Try guessing the answer

Screenshot (127) (2).png

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