JavaScript

Beginner’s Guide to JavaScript Closures

Closures” are among JavaScript’s most fundamental building blocks. As a JavaScript beginner, you may have utilized closures knowingly or unknowingly; however, gathering knowledge about the working of Closures is crucial as it enables you to understand the interaction between variables and functions and the execution process of your JavaScript program.

This write-up is a complete beginner’s guide to JavaScript Closures in which we will discuss the variable access within different scopes.

Before diving into the concept of JavaScript Closures, we will first explain what Lexical scoping is as both terms are associated with each other.

Lexical scoping in JavaScript

The variable scope is determined by its declaration in the source code, known as “Lexical Scoping”. For instance, in the below-given example, the created “name” variable is a “global” variable which signifies that it can be accessed from anywhere in the program, such as within the “displayMessage()” function.

However, “info” is a “local” variable that can be only accessed within the “displayMessage()” function:

let name = 'Alex';
function displayMessage() {
    let info= 'Hello! My name is';
    console.log(info + ' '+ name);
}
displayMessage();

Execution of the above-given code will show the following output:

Nested Lexical Scoping in JavaScript

The scopes of the variables can be nested using the “Lexical Scoping” in such a way that the inner function can have access to the variables declared in the outer scope.

Consider the following example:

function displayMessage() {
    let info= 'Hello! My name is Alex.';

    function show() {
        console.log(info);
    }

    show();
}
displayMessage();

In this example, the “displayMessage()” function has a local variable named “info” and a nested “show()” function, where “show()” is an inner function that has the capability to access the value of the “info” variable from the outer scope.

So, when the “displayMessage()” function is executed, it will call the “show()” function, which will then access the “info” variable and display its value on the console:

Now, we will modify the “displayMessage()” method and instead of invoking the inner “show()” function, we will add a statement to return the “show()” function object:

function displayMessage() {
  let info= 'Hello! My name is Alex.';

  function show() {
        console.log(info);
    }

    return show;
}

Also, we have assigned the value returned by the “displayMessage()” function to “x” variable:

let x = displayMessage();

Lastly, we will invoke “x()” function that refers to the “show()” function:

console.log(x());

You can see from the given output, the value of the local variable “info” still exists which generally remains in the memory till the execution of the function where it is declared:

Seems confused? This is the magic of Closure which you have seen in the last example as “show()” is a closure function that maintains the outer scope in its own scope.

What are JavaScript Closures

JavaScript functions also serve as “Closures” because the body of a function has access to the variables that are defined outside of it. Or we can define “Closure” as a function that is a child function and can access the variables created within the “parent” function scope.

Now, let’s check out some examples to understand the association between the variable scopes and Closure in JavaScript.

Example 1
This example demonstrates how a “local” variable “info” can be accessed inside the “show()” function where it is created. Remember, the remaining script cannot access this “info” variable:

function show() {
let info= 'Hello! My name is Alex.';
return info;
}

show();

When the “show()” function is executed, it will display the value stored in the “info” variable:

Example 2
Now, we will declare “info” as a “global” variable which is referred in the “show()” function (having different scope):

let info= 'Hello! My name is Alex.';
function show() {
return info;
}

show();

As the JavaScript function “show()” function is a “Closure”, it will maintain the scope and state of the “info” variable:

Example 3
In another situation, when variables are defined in the scope of the “parent” function, the “child” function can still access their value:

var displayMessage= function () {
    let info= 'Hello! My name is Alex.';
    var show= function () {
          console.log(info);}
}

show();

The output of the given program signifies that “show()” which is a child function, can access the “info” variable declared in the “displayMessage()” parent function:

That was all essential information related to JavaScript Closures. You can further research according to your requirements.

Conclusion

JavaScript functions also serve as Closures because the body of a function has access to the variables that are defined outside of it. We can define Closure as a child function that can access the variables created within the parent function scope. This write-up is a complete beginner’s guide to JavaScript Closures in which we have discussed variable access within different scopes.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.