JavaScript

JavaScript Function closures | Explained

After the arrival of the ES6 version of JavaScript, there are still a lot of features that are rather confusing to the masses. JavaScript is widely known to have a solution to every problem, and implementation of most (if not all) concepts. One of such concepts is the concept of Closures

The concept of closures has been around for quite some time now, but people have difficulty understanding it. We are going to go over step by step and make it really easy to understand with the help of examples.

What are Closures in JavaScript

Very briefly, Closure is having access to the outer scope from the inner scope when working with nested functions. A closure is created every time a nested function is executed in JavaScript. The variables defined inside the function are created on function execution and are removed from the memory upon the complete execution of the respective function.

To understand the concept of Closures in JavaScript we need to know the difference between the global scope and the local scope. Well, we are going to go over these really briefly.

Scopes of Variable

As mentioned above, there are two major variable scopes in JavaScript:

  • Global scope
  • Local scope

The variables defined outside of any function are known as global variables and have a global scope. These variables can be accessed from anywhere inside the program, that is why we use the term “global”.

Comparatively, the variables defined inside a function are known as local variables and are known to have a local scope. Local scope is further divided into function scope and block scope but that is not a major concern for us. Local variables can only be accessed from within the function in which they are declared

Take this block of code to understand the scope:

var siteName = "LinuxHint!";

function printSiteName() {
  let topicName = "JavaScript";
  console.log(siteName);
}
printSiteName();

console.log(topicName);

What we are doing in the above code is that we are creating a global variable siteName and we are printing it inside a function called printSiteName(), this function includes a local variable topicName and we are trying to print out the value of this variable outside of this function. Here, siteName is a global variable and topicName is a local variable. The output of the following code is as:

As you can clearly see, we were able to access the siteName variables inside a function, but we were not able to access the local variable topicName outside of its function. You can learn more details about these different variables and scope.

How does a Closure work in JavaScript

Now that we know how scoping works in JavaScript, we can easily understand the working of closures.

Closures are functions that are nested inside each other in such a way that the inner function becomes locally scoped for the outer function, and the outer function becomes globally scoped for the inner function. Meaning that the inner function has access to the attributes of the outer function.

For better understanding, take the following code:

function outerFunction() {
  let outVar = "I am outer";

  function innerFunction() {
    let inVar = "I am inner";
    console.log(outVar);
    console.log(inVar);
  }
  return innerFunction();
}
outerFunction();

We are creating an outerFunction and an innerFunction inside the outerFunction. From the inside function, we are accessing the variable outVar which is the local variable of the outerFunction, and printing its value along with the value of the variable inside the inner function.

This is how this code works:

The output of the above code is:

We were able to get the values of both the variables and print them out to the console using the console.log() function.

How to have multiple functions inside another function in a Closure

If we refer to the outer function as the parent function of the closure and the inner function as the child function of the closure. Then we can put it this way that a single parent can have multiple children. A parent function will not have access to the attributes of its children. However, every child will have access to the attributes of its parent. Since, a child function is also an attribute of the parent, so a child function can also access the other child functions of the same parent; this means having access to its siblings.

Note: Parameters and arguments are also accessible to children.

Suppose that we want to make a function that greets a function that calls it. This function has 3 parameters, firstName, middleName, and lastName.

First, create the function using the following lines.

function greeter(firstName, middleName, lastName){

    // later commands inside here
}

This greeter function is a parent function with four children. 3 of the children work on the parameters and return the value of the parameters like:

function getFirst() {
    return firstName;
  }
  function getMiddle() {
    return middleName;
  }
  function getLast() {
    return lastName;
  }

The last child, calls all of its siblings and prints the values on the console, which is implemented with the following lines:

function namePrinter() {
    console.log("Welcome! " + getFirst() + " " + getMiddle() + " " + getLast());
  }

At the end of the parent function greeter() it returns the namePrinter() child to the place where it is called.

To, execute this whole Closure we need to call the parent function with the following line:

greeter("John", "Bukhari", "Doe");

The complete code snippet of this closure is:

function greeter(firstName, middleName, lastName) {
  function getFirst() {
    return firstName;
  }
  function getMiddle() {
    return middleName;
  }
  function getLast() {
    return lastName;
  }

  function namePrinter() {
    console.log("Welcome! " + getFirst() + " " + getMiddle() + " " + getLast());
  }
  return namePrinter();
}

greeter("John", "Bukhari", "Doe");

We will get the following output:

Conclusion

The closure is a feature that came with the ES6 release of JavaScript. Closures are the implementation of the concept based on the scoping of variables in JavaScript. We learned what closures are and since they are based on scoping of variables we learned about scoping as well. We went through the difference between global scope and variable scope in Js, and in the end, we tested out the working of closures with the help of examples.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.