The inner function preserves the scope chain of the enclosing function or the outer function at the time when the outer function was created. Thus the inner function will have access to the variables and arguments of the outer function in its scope chain even after the outer function completes execution.
So Closures provides us a way to still have access to the variables inside the function that has completed its execution.
Let's look at this concept with an example.
In the above piece of code the inner function that is returned from the outer function forms a closure with its parent. So, essentially the inner function will have access to the following when it is executed-
- Variables and Arguments within the scope of the inner function.
- Variables and Arguments of the outer function to which the inner function forms a closure
- Global variables
Closures gives us a way to preserve the scope chain of outer functions even after it completes its execution. One use case of this is Data hiding/ Data Privacy.
So in other words, we can say that closures are functions that have access to all the variables in scope when it was declared.
A major disadvantage of closure is that proper garbage collection does not occur if there are closures. The variable environment of the outer function will not be cleared if there is an inner function forming a closure with the outer function. This can lead to memory leaks.
HOCs are functions that take one function as an argument or returns a function.
If there is a use case to change the style properties dynamically and later if the user wants to return to the initial style, we can keep the initial style state saved and access it using closures.
Example given below -
In the above example we can see that font-size and color property for the sampleText class is being set manually in the beginning. Afterwards the font-size is updated using the updateStyleProp closure function. But even after updating the styles manually, the getInitialState closure function which has access to the intialState variable in the outer function is able to print the initial values.
As shown in the code above, the maleGreeting and femaleGreeting variables are accessible within the greetMale() and greetFemale() functions which form a closure with the singleton function greeting().
Closures are cornerstone to functional programming!