DEV Community

Cover image for Closures and Lexical Scoping in JavaScript
Amitav Mishra
Amitav Mishra

Posted on • Originally published at jscurious.com

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 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 parent’s scope i.e. inner functions can access the global variables.

var a = 5;

function sum() {
    return a + 6;
}

console.log(sum()); // 11
Enter fullscreen mode Exit fullscreen mode

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

Closure

var a = 5;

function sum() {
    return a + 6;
}

console.log(sum()); // 11
Enter fullscreen mode Exit fullscreen mode

A Closure is a function which has access to the parent scope variables. The above function has access to 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.

closure-javascript-jscurious

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
Enter fullscreen mode Exit fullscreen mode

When you call sum(5), it returns a function which 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.

closure-javascript-jscurious

You may also like

Thanks for your time
Find more Web dev blogs on jscurious.com

Top comments (0)