JavaScript Closures

JavaScript Closures

You need to know how the lexical scoping works first to understand the closures.

Lexical scoping Lexical scoping defines the scope of a variable by the position of that variable declared in the source code. For example:

let name = 'Ravindra';

function greet() { 
    let message = 'Hello';
    console.log(message + ' '+ name);
}

The variable name is a global variable. It is accessible from anywhere including within the greet() function. The variable message is a local variable accessible only within the greet() function.

If you try to access the message variable outside the greet() function, you will get an error.

So the JavaScript engine uses the scope to manage the variable accessibility.

According to lexical scoping, the scopes can be nested and the inner function can access the variables declared in its outer scope. For example:

Closures

In JavaScript, closure provides access to the outer scope of a function from inside the inner function, even after the outer function has closed. For example,

function outer(){
    let count = 0;
    function next(){
        return count ++;
    }
    return next;
}

let getNext = outer();
 getNext(); //1
getNext();// 2 
getNext();//3

In simple, a function along with its lexical scope bundle together to form a closure

The closure concept exists for other programming languages like Python, Swift, Ruby, etc.

Let's have a look at another example.

function z(){
var b = 500;
function x(){
var a = 590
function y()){
console.log(a,b);
}
y();
}
x();
}
z();

//Output => 590,500

VwfKlqu.png