JavaScript Closures are not that scary!

What is closure in JavaScript?

The closure is a combination of functions and its lexical scope bundles them together.

Let’s explain closure with an example

Explanation: In the above example, we can see that a function returns another function which is called the child function, and the child function returns the result. The parent function accepts 2 parameters that are available in the scope of the parent function. The child function can access the variable of the parent function because they are present in the same scope. The child function sets the parent function property in its scope property as closure.

When we write to console.dir(parent(1, 2)) it return the child anonymous function and we can see something like below,

We see that the child function has a scopes property where the closure property is present and the parameter of the parent function is present inside the closure. The closure stored the variable as a reference, which means it carries only the memory address of the variable, not the exact variable. Global property is also one kind of closure. It contains global variables into the child function. That’s why child function can also access global variables inside the function scope.

I hope you understand….!!!!

When we declare a variable as the same name in the global scope and function scope what will be happened?

If that is the condition, the compiler takes functional scope variable value, not global scope variable value. To explain that case we need to know about scope. The rule of compilation is at 1st compiler search the value of a variable in function own scope, if the variable is not found then it will search the variable in the outer scope. It will be a function or global scope. If the variable will find the that will be executed and if another same variable declares over the outer scope or in the global scope that will be ignored.

Let’s learn that with an example:

In this example, we see that the variable a is declared in the global scope and in the outer function scope also. Another variable b is also declared in the parent function and in the child function. As the result(a + b) returns from the child function so at 1st compiler search for a and b in child function scope, in child function scope it will find the variable b that’s why it stops to search variable b and take value for b is 10 and search for variable a. The variable a is not defined in child function that’s why it search variable a in the outer function scope which is parent function scope. In parent function scope it will find variable a which value is 2 and stop to search for a. The global variable a is ignored in that case. In parent function, variable b is also defined but it will not be accepted, because in child function variable b is defined and the compiler takes that value for b.

That’s why the output of that function is 12, a=2, and b = 10.

Some advantages of closure:

  • With a function closure, you can store data in a separate scope, and share it only where necessary.
  • Closure helps to hide the data which is called data encapsulation.
  • It is used in function currying in JavaScript.
  • It is also used to prevent code repetition.

How to hide data using closure?

Let explain it with an example

The output of that code is 2 and 3.

In this example, the variable counter is defined in the global scope as a public variable. That’s why any function can access that variable, which is unexpected. That also will return garbage value.

If we want to hide that variable we need to write that variable inside the parent function or in the child function. Then this variable will be the functional scope variable. Outside of that function, this variable can’t access. This is called a private variable. That’s how we can hide data using the closure.


How to make Reusable code using a closure? (Explain with the previous example)

we can also call the parent function many times as counter2, couter3, couter4, and so on. Every time we will create a new increment counter. For every counter, it counts from 1. We don’t need to repeat the same code to create more counters.

Some disadvantages of closure:

  • Need more memory to compile closure because every time closure is invoked it creates a new instance for every time.
  • Sometimes it will not be garbage collected, that’s why it consumes a lot of memory.
  • If we can’t handle closure properly it makes memory leak and sometimes it makes our browser hang.

Let’s explain how garbage collectors work with the closure

At first, we need to know what is the garbage collector.

Garbage collector: Garbage collection (GC) is nothing but collecting or gaining memory back that has been allocated to objects but which is not currently in use in any part of our program. The main mission of the garbage collectors is to clean up the computer memory. Learn more about garbage collectors.

Now talk about how garbage collectors work with closure.

In this example, the variable count is defined in the counter function. When we call counter function then it needs to remove the function from memory because it is compiled already. But the counter variable is not removed from memory because it will need when we call child function. That’s why it needs extra memory to store that value. After invoking the counter1 function it still stores the reference of that variable because JavaScript doesn’t know how many times that closure is used in this program. That’s why it makes memory leak in the program if the programmer does not maintain closure properly.

How to optimize our code after invoking closure to prevent memory leaks?

JavaScript is an automatic garbage collected language. Every unnecessary object collect by the garbage collector and remove from the memory automatically. As JavaScript doesn’t know when the closure is unused that’s why so many closures make memory leak in a program, it is manually written by the programmer when the closure is useless.

For example:

In this example, the programmer knows that the counter1 function is no longer needed that’s why the programmer manually deletes that closure function from the memory and prevents the memory leak. It makes the program faster.

So that’s all for today’s article. If you feel any confusion please feel free to ask me in the comment. I will try my best to explain.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store