Intoduction :

When we are talking about the closure in javascript then most of us have no clear idea about what is closure and what is the use of this, when I am start learning js closure then it is a most confusing concept to understand.

In this article, I will try to explain closure in a very simple term with example.

What is Closure :

Closure means that inner function always persists the properties(like parameter and variables) of the outer function.

Still, it is sound like confusing, don’t worry let’s understand by an example.


function outerFunction(param) {
return function innerFunction() {
return param*2;
}
}
const obj = outerFunction(5);
obj(); // output : 10

In the above example, as you can see that when we are calling outerFunction with parameter 5 , the innerFunction persist the value of outerFunction i.e 5 whenever you call innerFunction, obj in this case(because we save result of outerFunction in obj ) the value of param inside in innerFunction always be 5.

Great, now we have a basic idea about closure. if it is still confusing for you let’s try to understand with the second example.

function outerFunction(param) {
return function innerFunction() {
return param*2;
}
}
const obj = outerFunction(5);
const obj1 = outerFunction(10);
obj(); // output : 10
obj1(); // output : 20

In the above example, we have a little bit modified the first example. As you can see that we are creating two instances of outerFunction, first time when we call outerFunction , obj(i.e instance of inner function) persist the value of 5 and when we call outerFunction with param 10 in this case obj1(i.e innerFunction) always persist value 10.