Closure in JavaScript

Closure in JavaScript

Closure is a very important topic in JavaScript. In this blog, we try to understand closure very deeply. Now, what is the closure?

A closure gives you access to an outer function’s scope from an inner function.

This definition will make sense when we try to understand this with example.

function outer() {
    const a = 10; // var, let, const all works
    function inner() {

        console.log(a);
    }
    inner();


}
outer();

Here, 10 should be printed. JavaScript finds the const a in the inner function first, then it finds const a in the lexical scope. The inner function can access the outer function's variable. In simple words, this is closure. But we will drive in deep of closure.

We understand that the inner function can access the outer function's variables. But what about outer function? Can the outer function access the inner function's variables? Let's figure it out.

function outer() {
    const a = 10; // var. let, const all works
    function inner() {
        var b = 11;
        console.log(a);

    }
    inner();
    console.log(b);

}

outer()

We get an error. That is b is not defined.

That's means, the outer function can't access the inner function variables under closure.

In closure, the inner function can also access the most outer and outer functions. Under this with an example.

function outest() {
    const a = 10;
    function outer() {
        console.log("outer a", a); //outer a 10
        const b = 11;
        function inner() {
            console.log("a", a); //a 10
            console.log("b", b);// b 11

        }

        inner()
    }
    outer();
}

outest();

Let's understand closure with more examples. What if, we try to declare same variable in the inner function? Which value should be printed?

function outer() {
    var a = 10;
    return function inner() {
        var a = 11;
        console.log(a);
    }
}


outer()();

Here, 11 should be printed. var a finds in the inner function first, when it doesn't find out. Then go to the outer function to find out the var a.

Let's try to understand what happens in the following code.

function outer() {
    var a = 10;
    function inner() {

        console.log(a);
    }
     a = 11;
    inner()
}


outer();

What should be printed, 10 or 11? The answer is 11. In the execution part of javascript, the value doesn't save. It saves the reference of the variable and the inner function always points to that reference.

Hopefully, you all understand the concept of closure. Happy Coding 👨‍💻