Closure In JavaScript is one of the hardest concepts to grasp for the JavaSript Developers. Coding in the JavaScript without knowing about the closure is like driving a car without knowing it’s driving features.

If you are preparing for the interview for the mid-level position in any company then this is one of their favourite questions for javascript developers. Companies like Amazon, Google, Apple also asked so many problems related to JavaScript Closures. So this is the most important topics in the JavaScript.

If you have a fear of closure in JS then after reading this article, you will become a master in the Js closure. 🙂

What is Closure in JavaScript

To understand what is closure, you first have to know about the local variable scope and function scope.

A closure is a function which has access to its parent scope, even after the parent scope closed.


Above line tells what is closure in javascript but what do those lines mean? Let’s understand the meaning of that line in details by a couple of examples.

Example 1

We all know that whenever we create a function in javascript, it has access to local and global variables. Variables created inside the function is called the local variable and variables created outside the function is called global variables.

function example(){
   let x = 3
   console.log(x);
}
example(); // 3
console.log(x); // Uncaught ReferenceError: x is not defined

In the above code, we created a function called example() and inside this function created a variable with name x and assign a value to it.

When you call the function then it will log the value but when you called the variable inside that function then we get a reference error. This is because x is locally scoped with function example and not available outside of that function.

Now take another code where we define x as a global variable like below

 let x = 3;

function example(){
   console.log(x);
}
example(); // 3
console.log(x); // 3

In the above code, we define x as a global variable and when we call the function example() and log the x then we will get both values now.

These two codes are simple and self-explanatory but think what will happen if we another function inside the example() function which does another task. Don’t have any idea? Let’s learn that also and then we will get the clear concept of the closure in javascript.

Example 1.a

function example() {
  return function add() {
    let x = 3;
    let y = 1;
    console.log(x+y);
  }
}

Example 1.b

function example() {
  let x = 3;
  return function add() {
    let y = 1;
    console.log(x+y);
  }
}

In the above two examples, we will get the same output 4. Looks like you confused, how this is possible, then look the definition of the javascript closure which you read a few minutes back at the above lines.

This is all because of the closure effect of the javascript.

Example 2

Let’s understand more about javascript closure with another example.

function Counter() {
    let counter = 0;
    return function IncreaseCounter() {
        return counter += 1;
    };
}

let count = Counter();
console.log(count()); // 1
console.log(count()); // 2
console.log(count()); // 3
console.log(count()); // 4

Above code is much similar to the previous one. Here, we are creating a Counter function which increments the value every time when this function called.

This is one of the most used functionalities of the closure in JS. Suppose you need to implement a counter function in your code and if you do it with simple function then it will reset that counter every time you call that function and if you define a global variable then other function can change that value.

Why We Use Closure In JavaScript

A good developer always wants their code to follow the coding standard and easy to use by simplifying the daily job. For the javascript developers, closure is one of those skills which make them do the advance level of coding and then can increase their productivity.

Below are some cases where closure saves lots of time of the javascript developer.

Data Encapsulation

Data encapsulation is one of the most used and important features in the programming. While writing code, we don’t want to expose all the details to the outer world. In javascript, By using closure, we can achieve this very easily.

let person = (function () {
 
  let fullName = "sachin jaiswal";
 
  return {
    setFullName : function (newValue) {
      fullName = newValue;
    },
    getFullName : function () {
     return fullName; 
    }
  }; // end of the return
}());

In the above code, we encapsulate the fullName variable by using the closure. In this code, we are returning two functions setFullName and getFullName which is used to set a new name and get the name of the person respectively.

If you try to use person.fullName then it will throw an error undefined.

To Animate a DOM Element

Let’s say you have a DOM element which value increases at the set time of interval. Then you can easily do that by using the javascript closure.

let count = 0;
let p = createP(count);
// Call countIt every 1 seconds
setInterval(incrementCount, 1000);

// Increase the count and set the new content
function incrementCount() {
  count++;
  p.html(count);
}

What is the Advantage of Using Closure in JavaScript

There are lots of advantage of using closure in javascript. Whenever you create a new function in javascript, it creates closure automatically.

Closure makes easy to follow the object-oriented programming style in JavaScript. You can easily singleton a class, encapsulate the data and do other things easily.

Conclusion

Hope, Now you have a clear idea of closure. It’s not difficult to understand but you have to look at different closure functions and function scope to become the master in the javascript closure.

Now next time when you see closure in any GitHub code or any other place then you can easily understand what they are doing.

If you want to know more about this in deep then I will recommend you to read the MDN Official docs on it or you can take any courses from the best online websites for learning web development like Codecademy, Udemy, Coursera, SimpliLearn.

If you have any doubt and suggestion then let me know in the comment section. And If you like this article then please share it.

Codecademy Web Development
Pin It