Closure in JavaScript

The closure is the most powerful feature of JavaScript. The closure comes into the picture when using nesting function. JavaScript allows functions to be nested. A function can be defined inside another function.
Inner function can access all the variables declared in the outside function. When inner function available outside, it still can access the functions declared in outside a function, and that is called a closure has created.
Function remember everything about where it was declared. When it is available outside, it still remembers the environment where it was created.
Remember, an outer function cannot access the variables inside the inner function.


function outerFunction(){
    let name = "dog";
    function innerFunction(){
        return name;
    }
    return innerFunction;
}
let foo = outerFunction();
console.log(foo());
//output: dog
                    

As you can see, when we call outerFunction, it returns innerFunction. Now innerFunction returns a variable name which is declared in outerFunction. Now, outerFunction returns innerFunction which is saved in foo. When we call foo, it calls innerFunction, which returns name.
It can be a little bit complex than above code.


function outerFunction(name){
    function innerFunction(){
        return name;
    }
    return innerFunction;
}
let foo = outerFunction("cat");
console.log(foo());
//output: cat

let foo1 = outerFunction("dog");
console.log(foo1());
//output: dog

console.log(foo());
//output: cat
                    

In above code, innerFunction also can access the parameters of outerFunction.

Private Variable

Sometimes, you don't want some other function to access some data. Then you can use closure. Let us have a look at an example.


let foo = (function(){
    let privateVar = "ab!23b*";
    function retFunction(){
        return privateVar;
    }
    retrun retFunction;
})();

console.log(foo());
//output: ab!23b*
                    

We already have seen self calling function. When self calling function executes, it returns retFunction creating a closure and assigned to foo. So it can access privateVar. So whenever you need privateVar, you just need to call foo. There is no way to change the privateVar.

Conclusion

In this section, you learned about the closure. The closure is a great concept. It will be very useful in JavaScript and You must master it.
In next section, you will learn about Array in JavaScript.