As the definition goes, closures are the inner functions in JavaScript, that has access to the private variables. If that is not enough, consider the following example for instance.
As shown in the code above, name is the property of the function Person and is accessible from the objects of that function. The output of the preceding method would be, yes you guessed it, Neelesh.
Now let's modify the code a bit and see what happens. Consider the following code.
The output of the code above will be like:
Let’s stop here for a moment and analyze what actually happened. Previously, the property name was the property of the function Person and therefore was accessible to every object of Person. Lately the property was changed to just be a private variable. On doing so, it loses its scope and became inaccessible. The objects of Person would now have no idea of whether or not the property name even exists and hence it has thrown "undefined’. Now, let us bring closures into the picture.
So, as you can see from the preceding figure, the function getName or our closure function as being the inner function of Person, can access its private variable. And this getName function, on being the property of the function Person, can be access by the objects of Person. The output if the code above would be:
Cool! Now if you look at it closely, there is a subtle difference between our first approach and this one however. In the former case, we can, at any point, modify the value of the variable name of the function Person that could lead to an adverse effect on our code at the latter stage. Like:
1: person.name = "This is the fake test name";
But with the latter approach, (the closure one, of course), we don’t have access to the property name at the first place and hence, we cannot modify it.
I hope this article leads to a basic understanding of closures.
Happy Reading!!!