Let's try to understand the concept of JavaScript Closures in depth
Tags: javascript, tutorial, webdev
Published: 2021-06-16 05:28:17

##Definition
*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.*

This is an important concept in JavaScript because in JavaScript, variables are only in scope during the lifetime of the function or when the function is being executed.

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.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gdgipux189hx0zorjy7i.png)
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gqyquzhlxdsj4pkenhm8.png)
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-  
1. Variables and Arguments within the scope of the inner function.
2. Variables and Arguments of the outer function to which the inner function forms a closure
3. 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.*

##Disadvantages of Closures
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.

##Common use cases of Closure

###Case 1 - Higher Order Functions (HOCs)

*HOCs are functions that take one function as an argument or returns a function.*

####HOC to create different multiplier functions
One example of HOCs which can be seen below is creating different multiplier functions that uses closures to create functions that can multiply a number with different values.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nyoxk27c9fnh7c6ce5fk.png)
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x0s8wjhlwehefkyv6wna.png)


####HOC to round numbers to a certain number of decimal places
Same way, we can also use closures to create functions that returns numbers fixed to different decimal places as shown below. 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ufhqa31snmxmqjesqw8l.png)
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s1i5a7kwlywgimxbqy5u.png)


###Case 2 - Creating a function for keeping track of old DOM styles and also updating the value

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 -
<figure>
<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r6qwkdwrgzt9tl88t3i4.png">
<figcaption>Fig shows a simple html file with a div with sampleText class being assigned font-size and color properties</figcaption>
</figure>

<figure>
<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4n5rimk2fvip57mqbaw4.png">
<figcaption>Fig shows the JS file that explains how the DOM style state can be kept in memory even after updating it, using closures</figcaption>
</figure>

<figure>
<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j0t9ok28vhn6et3v7ixl.png">
<figcaption>Fig shows that the font-size and color has changed in the app, but the closure still has access to the initial styles</figcaption>
</figure>

<!-- This won't show up in the content! -->
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.  

###Case 3 - Singletons

*Singletons are a type of JavaScript design pattern in which one class is instantiated only once and only that one class is made available publicly.*

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/166ohu9clkwg6g90sioa.png)
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v9li179krds797xjrz9g.png)

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()*. 

###Case 4 - Data Hiding

Closures are the means for creating private variables in JavaScript as shown below -

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fmcawr6l97y8h6dlxk9e.png)
 
##Conclusion

We have understood the concept of closure and seen some examples of how and where they are used in the JavaScript programming language.

**Closures are cornerstone to functional programming!**