Skip to main content

Command Palette

Search for a command to run...

Closures in JavaScript

Updated
1 min readView as Markdown
Closures in JavaScript

The closure is a collection of functions with a lexical environment.

Meaning of Lexical Environment/ Scoping

The scope has the ability of function scope to access the variables from the parent scope.

Here have some examples:

First example:

let a = 10;

function total(){
        console.log(a);
}

total()

//ans
10

In this example, we can see a normal function.

Second Example:

function total(){

    function add(){
        let a = 10;
        console.log(a);
    }
    add()
}

total()

//ans
10

In the second example, we can see the function inside one more function has been created and inside only we had called the function. In the same way, we can create more functions inside the parent function and also call the function inside.

Third Example:

function total(){

    return function add(){
        let a = 10;
        console.log(a);
    }

}

total()()
// ans 
10

In this third example, we can return directly to the function and we can call the function by giving two "()()" brackets, only two brackets will work when the parent function has one child function, we want to access more child functions means we will use "Destructuring". For more information about Destructuring please go through the article link of Destructuring