I have seen many blogs and videos trying to explain closures but in a very complicated way. Here is the easiest and simplest way to get them in your mind. I will start off simply and magically (if there was such a thing) land up explaining you closure.
Firstly , just look at this piece of code below:
Here we can clearly see that timmy function can access the variable b.
Now what if I change the value of variable b to 3 on line 2 and run the code again?
Of course the output would be 3.
Lets dive deeper
Now look at this piece of code now:
What happens here ?
But why are we attaching values of the outer scope to the created function? The answer is what if we want to call a function outside its scope(through reference). Lets see how.
Take a look at this code:
Here, c is not in the reach of function a and b but still they show c as 3 and 4. Surprised?How did this happen?
Think a bit and you will notice that the returned anonymous function in both the cases have their own copies of c attached to them and when they are called, they use their own copy of c .
Well ,in simple words that is closure. A function has a copy of the whole chain of variables in outer scope , and when it is called anywhere(through reference) it will easily recall all its outer scope variable at the time of its creation.
In the above code when you add the following code:
You would see the copies that were made.
Now I hope you have understood what closures are .
Allow me to recall the first example :
Do you really think there is need for copies of global variables to be attached with functions? The answer is no. Why?
so if you do a console.dir(timmy) for above code then you would see global variable b under global tag:
In the beginning, I said that I’ll explain closure to you in the most simplified way. Here we are at the end and I hope I did a good job.
Well this sums up this post.
Explore more , code more.