Closures in JavaScript
Tags: javascript, webdev, 100daysofcode
Published: 2022-10-21 07:36:49

In this blog, I have told everything about closures.

- **What are closures?** 

Closures are a combination of a function and its lexical scope bundled together to form a closure.

A function along with reference to its outer environment together forms a closure.

Every function in JavaScript has its axis to its outer lexical environment i.e. access to every variable present in its parent environment. So even if this function is executed in some other scope it still remembers its outer lexical environment where it was originally present in its code. This is what closure is.

Example-

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hycjhdijqc5lbh7ejt1o.jpg)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/81jv1adb9y9l6f5om48y.jpg)

Line 3 to 5 along with its outer lexical environment forms a closure. The two parentheses used in line number 9 are used to call the inner function. The closure also doesn't follow any sequence. If we move line number 2 to after line number 5  then also inner function with its outer environment will form closure.


If we use the **Let ** variable also then also it will give the same output.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yl54ka5jgn1acmzgylld.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m580by5z8r3frmjifiv7.jpg)

If we give a parameter in line number 1 then also the inner function will print the parameter value because the inner function had formed a closure with its outer environment.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3b6x6j9su2w2ua2t0jg4.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s864d7o9g1y3mm5u1wcu.jpg)

Even if the outer function is nested inside another function, then also inner function will have access to the variable of the outest function.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/japm2vbiva2z2z0kbmtg.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fb830w1qjybgsifvv3s5.jpg)

If we give a conflicting let variable on line number 12 then also it will print 10 because it has accessed the line number 7 variable. 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kkl5t12zauffbipepbja.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xfrrsznp3ieqrh7tbv4e.jpg)

But if we remove line number 7 then it will go deeper in the hierarchy and at last, it will to the global scope to resolve this let variable and it will print its value.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rm8s7mnut28z3p99m6bm.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/599jpvwmveg30dx049pl.jpg)

## Advantages of Closures

Closures are the most beautiful and important part of JavaScript. It has many advantages.

1. It is used in module patterns.

2. It is used in function courring.

3. It is used in higher-order functions like memoize and ones.

4. The most important use is in **Data hiding** and **encapsulation**.


**Data Hiding-** Suppose we have one variable and we want to protect it. We don't want other functions and code to have access to this data. In other words, we can say that we want to encapsulate this data from other pieces of code.

Example-

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/46rogrvxa44wh1ljhhmg.jpg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ngczioa3hfmfwzbgd7vn.jpg)

In the above example, we can see that we have made a function and protected our count variable. No one from outside can have access to it.

To get access we have to add a return function in line number 3 and it will form a closure.
We can create a variable counter1 and call it to access to count variable.

Example-

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8zkfymnu2158bc6gfhm5.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9yhxbq75bhn2hlgqhtmf.jpg)

If we create a new variable counter2 and call the counter function then it will create a new closure and the count variable will again start from 0.

Example-

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/40ogqphoqx95ngm1yjvk.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/en6dxyykb491a4jpszjt.jpg)

In the above image, we can see that the first two output is from counter1 and the third one is from counter2.


If want to make this code good and scalable then we can do this which I have shown in the example below. I have created a constructor here. It will still form closure and our data is protected.

Example-

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qfvljnqvlk7si0qyq5ye.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w9grb3pfpyg942iy76yr.jpg)

**Disadvantage of closures**- The major disadvantage of closures is that sometimes there can be over consumptions of memory in a closure because every time a closure is formed it consumes a lot of memory and sometimes those closed-over variables are not garbage collected before the program expires. If this is not handled properly then it may lead to a memory leak and may freeze the browser.

**Garbage Collector**- It is in the JavaScript engine to freeze or take the variables which are not used. 

Garbage collectors and closures are related to each other.
In the below example, we can see that in line number 3, variable x and z both of them form a closure but when z is not used then in modern JavaScript engines line V8 it is garbage collected and freed from the memory. That is why it gives not defined when we try to access it.

Example-

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w81zwbje0tbbtfzqg4jz.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lrppqpghnzan1jhhjtf.jpg)

This is all about closures. I have read all this from the [Namaste JavaScript](https://www.youtube.com/playlist?list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP) series by [Akshay Saini](https://twitter.com/akshaymarch7). If you want to fall in love with JavaScript then you should learn from this.