Closures and Lexical Scoping in JavaScript

Variables in JavaScript have two types of scoping i.e. Local and Global scope. If any variable is declared inside a function, then it is a local variable and if the variable is declared outside the function then it is a global variable. The scope of variables is defined by their position in the code.

Lexical Scope

JavaScript follows Lexical scoping for functions. Lexical scope means any child’s scope has access to the variables defined in the parent’s scope i.e. inner functions can access the global variables.

var a = 5;

function sum() {
    return a + 6;
}

console.log(sum()); // 11

In the above example, function sum() is using the global variable "a" to perform the addition.

Closure

var a = 5;

function sum() {
    return a + 6;
}

console.log(sum()); // 11

A Closure is a function that has access to the parent scope variables. The above function has access to the global variable “a”, so it is a closure. If you will do console.dir(sum), then you can see inside [[scopes]] property, the global variable “a” is present.

Now let’s see another example of Closure with respect to inner function.

function sum(outerValue) {
    return function(innerValue) {
        return outerValue + innerValue;
    }
}

const findSum = sum(5);

console.log(findSum(10)); // 15

When you call sum(5), it returns a function that holds the variable outerValue. So when you call findSum(10), it adds the outerValue value with innerValue. The inner function holds the outerValue even after the outer function is closed, this is called closure. If you will do console.dir(findSum), you can see inside [[scopes]] property, the outerValue is present.

Leave a Reply

Your email address will not be published. Required fields are marked *