JavaScript Closures

JavaScript Closures with Examples

In this article, I am going to discuss JavaScript Closures with Examples. Please read our previous article where we discussed Prototypical Inheritance in JavaScript. In this article, first, we will discuss the basic concept of closures and then we will see how JavaScript Closures helps us to implement proper object-oriented programming concepts in JavaScript.

What are Closures?

In simple words, Closures are nothing but Stateful Functions. When we create any function in JavaScript then by default it is stateless. For better understanding, please have a look at the following example. Here, we created a function called Counter and inside this function, we created a variable called count and we increment that count variable value by 1 each time the function is called and log that incremented value. Then we call the Counter function two times.

<html>
<head>
    <title>JavaScript Stateless Example</title>
</head>
<body>
    <script>         
        function Counter() {
              var count = 0;
              count ++;
              console.log("Count : "+ count);
        };
        Counter(); //First Call
        Counter(); //Second Call
    </script>
</body>
</html>

Output: Now run the application and have a look at the browser console window. You will see that for both the function call it will print the same value 1 as shown in the below image.

What are Closures?

We are getting the same value for both calls. This is because it will create a separate state for the count variable for each function call. That is, for the first function call it maintains one state and for the second function call, it maintains a different state for the count variable.

Technically this is current. Because when a function or method runs, it creates running memory for all the variables (example count) inside the stack. And once the function call ends, the memory released from the stack. For better understanding, please have a look at the below image. The following things happen in order for each time the function Counter is called.

JavaScript Closures with Examples

But sometimes we want the function and variable should stay in the memory. For example, every time we call the function Counter, the value of the count variable to be incremented. In other words, we want the count variable to be remembered.

One of the ways you might be thinking let’s go and declare the count variable globally as shown in the below example. So, every time the Counter function executed, the count variable value gets incremented.

<html>
<head>
    <title>JavaScript Stateless Example</title>
</head>
<body>
    <script>   
        var count = 0; //Declare Globally
      
        function Counter() {
              count ++;
              console.log("Count : "+ count);
        };
        Counter();
        Counter();
    </script>
</body>
</html>

Output: This will give the output as expected as shown in the below image.

JavaScript Closures with Examples

What is the problem with the above approach?

Let us understand the problem with the above approach where we declared the count variable globally. One of the rules of good programming is that modules, functions, methods, should be self-contained. But if you declare the variable globally, then you may face some problems. For example, the global variables can be accessed by any function. If we have another function, then that function also accesses the count variable and changes the values. We cannot restrict this as the count variable is global.

What is the problem with the above approach?

For a better understanding, please have a look at the below example. Here, the count variable is accessed by both the Counter and MyCounter functions. As our requirement is only to increment the count value by using the Counter function, but here we are also able to increment the value by using the MyCounter function which results in inconsistent output.

<html>
<head>
    <title>JavaScript Stateless Example</title>
</head>
<body>
    <script>   
        var count = 0; //Declare Globally
      
        function Counter() {
              count ++;
              console.log("Count : "+ count);
        };

        function MyCounter() {
              count ++;
              console.log("Count : "+ count);
        };

        Counter();
        MyCounter();
        Counter();
    </script>
</body>
</html>

So, what we want is, want the count variable to be private and should have a different instance altogether. This where exactly closures come into the picture in JavaScript. Closures help us to achieve Isolated Stateful functions.

What is a Closure in JavaScript?

A Closure is nothing but a function inside a function. In other words, one function enclosed another function and this is the reason why it is named Closure.

What is a Closure in JavaScript?

Let us see how to write a closure in JavaScript. Please have a look at the below image. We have the Counter function and inside the counter function, we created another function called Increment and we move the logic inside the Increment function i.e. increment the count variable and log the value in the console. Then we return that Increment function from the Counter function. Later part of this article, we will discuss the return statement in detail.

What is a Closure in JavaScript?

Now, you can create a different object of the Counter function and can call the Increment function as shown in the below image. For the first object (i.e. counter1) we call the increment method two times, so you will get the output as 1 and 2. Again we create another object (i.e. counter2), for this object, it will create a different instance altogether and as you can see we call the Increment method two times, so again you will see the count value as 1 and then 2 as expected.

How to Create Closure in JavaScript

Example: JavaScript Closure Example
<html>
<head>
    <title>JavaScript Closure Example</title>
</head>
<body>
    <script>   
        function Counter() {
              var count = 0;
              // The Increment function is ENCLOSED 
              // inside the Counter function
              var Increment = function(){
                  count ++;
                  console.log("Count : "+ count);
              }
              
              return {
                  Increment
             }
        };

        var counter1 = new Counter();
        counter1.Increment(); //1
        counter1.Increment(); //2

        var counter2 = new Counter();
        counter2.Increment(); //1
        counter2.Increment(); //2
    </script>
</body>
</html>
Output:

How to Create Closure in JavaScript

So, here in every call, it is remembering the local variable count. Now the question comes, in reality, while we are doing the project, what is the use of such isolated stateful functions (i.e. closures). The simplest answer to this question is, closures help us to implement object-oriented programming concepts in JavaScript.

Why we need Closures in JavaScript?

Let us proceed and understand how closures help us to achieve the OOPs concept in JavaScript.

The OOPs Concepts:

Object-oriented programming provides four concepts. They are as follows:

  1. Abstraction: Show what is necessary
  2. Encapsulation: Hide the complexity
  3. Inheritance: Parent-Child relationship
  4. Polymorphism: Depending on the situation the object behaves differently
How the above Principles are Implemented using Closures?

Let us first see an example for abstraction and encapsulation i.e. we will see how to achieve abstraction and encapsulation using a closure in JavaScript. Please have a look at the below image. As you can see in the below image, first, we created the Employee object using the constructor function and then add some properties (_FirstName, _LastName, and _EmployeeCode) and functions (_AddEmployee, _Validate, and _DbConnection). Within the _AddEmployee method we are calling the _Validate and _DbConnection method. By default, all the properties and functions are made private and hence we achieve Encapsulation. Abstraction says show only what is necessary. So, in our example, we want to show the _FirstName, _LastName, _EmployeeCode, and _AddEmployee method to the end-user. But we don’t want to show _Validate and DbConnection method. So, in the return statement what you want to expose to the end-user just mention i.e. they become public. So, while I am making something public, I want to give some meaningful names. For example, _FirstName to be called by FirstName from outside. In the return statement, we mention the FirstName, LastName, EmployeeCode, and the AddEmployee method which means these properties and methods have now become public and the end-user can access these methods and properties. But the end-user cannot access the Validate and DbConnection method. This is nothing but Abstraction i.e. show only what is necessary.

How OOPs Concepts are Implemented using Closures?

In this case, when anybody sets or gets the value of FirstName, it internally set or gets the value from _FirstName property. Same for _LastName and _EmployeeCode. When anybody calls the AddEmployee method, internally the _AddEmployee method is invoked. Now, you can create an object of Employee and can set the values of FirstName, LastName, EmployeeCode, and can invoke the AddEmployee method as shown in the below image.

How OOPs Concepts are Implemented using Closures?

Example: Implementing Encapsulation and Abstraction in JavaScript using Closure

The complete code of the above-discussed example is given below.

<html>
<head>
    <title>Encapsulation and Abstraction in JavaScript using Closure</title>
</head>
<body>
    <script>   
        function Employee() {
              //Declare methods and properties as private i.e. Encapsulation
              var _FirstName = "";
              var _LastName = "";
              var _EmployeeCode = "";

              var _AddEmployee = function(){
                   _Validate();
                   _DbConnection();
                   console.log("Employee Added into the Database");
              }

              var _Validate = function(){
                   console.log("Employee Validated");
              }

              var _DbConnection = function(){
                   console.log("Database Connection Successful");
              }

              //Abstraction: Show only what is necessary
              return {
                  FirstName : _FirstName,
                  LastName :  _LastName,
                  EmployeeCode: _EmployeeCode,
                  AddEmployee : _AddEmployee
              }
        };

        var Emp1 = new Employee();
        Emp1.FirstName = "Anurag";
        Emp1.LastName = "Mohanty";
        Emp1.EmployeeCode = "Emp1001";
        Emp1.AddEmployee();
       
    </script>
</body>
</html>
Output:

Implementing Encapsulation and Abstraction in JavaScript using Closure

So, with closure, we implement Encapsulation and Abstraction in JavaScript. Please read our previous article where we discussed Inheritance in JavaScript. As JavaScript is a dynamic language, there is always polymorphism i.e. any variable can become any data type.

In the next article, I am going to discuss IIFE in JavaScript with Examples. Here, in this article, I try to explain JavaScript Closure with Examples. I hope you enjoy this JavaScript Closure with Examples article.

2 thoughts on “JavaScript Closures”

  1. Nice explanation of closures,looks like es-06 classes,actually doing the same job because es-06 class is only funkction sintatic suggar.

  2. In the last example, when we try to set the value of _FirstName with emp.firstNames instead of emp.firstName, then also it’s working properly, how the mapping is working in this?

Leave a Reply

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