Hi friends, in this post we will see what is mean by the closures and why it is so important for every developer to understand it. Closurers is one of the most important topic when it comes to javascript or front-end interview preparation.

Now lets talk about what exactly the closure is?

Closure is nothing but the function along with its lexical scope environment. I hope you are familiar with what lexical scope is?

If not please whatch this video on youtube posted by Akshay Saini where he described about lexical environment in very simple way (Lexical Environment).

Let me give you a simple example on closures. Suppose we have function called as inner() nested inside an another function called as outer() and we want to access variables present in outer function inside the inner funtion.

In above example when we are invoking the function outer(), it console logs the output as 7. Because function inner() forms a closure wth its parents lexical environment and hence we are able to access the variable a inside our inner() function.

Lets see an another example of closures to better understand the topic. Suppose we want to print number from 1 to 5 with with delay of 1 sec for number 1, 2 sec for number 2 and so on.

To solve the above problem most of the developers will simply write a for loop and use setTimeout within the loop like below and we will get that weird ouptut.

Why it is behaving like this….? Let me break the code and explain to you what exactly is happening here. So in above code var i is getting incremented from 1–6 and setTimeout is set for each iteration having refernce of i, by the time console.log(i) runs the variable i will be having the value 6 in it and hence it print 6 every time.

So how do we solve the above problem using closure. Let’s see the below code.

This time we are calling the function y(t) for each iteration of i and it creates the new copy of i for itself and it is being passed to setTimeout function respectively.

So final concusion is “Closure is nothing but the bundle of function with its lexical environment”.

If still you are not clear with what the closure is? I will recommend to watch the Closure video on Akshay Saini’s Youtube Channel. This post is also written by watching his Namaste Javascript series.

Full Stack Developer