DEV Community

Cover image for Closures in Javascript.
Abhishek Jain
Abhishek Jain

Posted on • Updated on

Closures in Javascript.

Closures in javascript is one of the many questions normally asked in javascript interviews.

What is a closure?

whenever a function is created, it forms a closure with the outer functions' scope. Think of that closure as a pack of All the variables of the outer function scope.

Let's understand this with an example.

  function createAdder(firstNum) {

    return function (secondNum) {   //The closure function
      return firstNum + secondNum;
    };

  }

  let addOne = createAdder(1);

  console.log(addOne(10)); // 11
  console.log(addOne(2)); // 3
Enter fullscreen mode Exit fullscreen mode

let's understand what's happening in the above code.

  • First we define a function createAdder that takes firstNum as a parameter.

  • Then, we return an anonymous function that takes a secondNum as a parameter.

  • Now, we declare addOne variable, with a call to createAdder function, with firstNum parameter value being 1.

      // so now the value of addOne should be -

      addOne = function (secondNum) {   //The closure function
                 return firstNum + secondNum;
               };
Enter fullscreen mode Exit fullscreen mode
  • so now, when we call addOne(10). how does this addOne get the value of firstNum? It's because of closure.

  • so when the anonymous function (returned function) is created. It looks for parent variables. It finds firstNum variable with value 1 and forms a closure with it (saves the variable) so that it can access the firstNum variable later.

  • so the addOne(10) function returns 11. Because it already has the firstNum's value as 1.

Now, I think you understand closure, Let's look at a practical example of where we can use closure.

In the above example, the updateClickCount variable is assigned to a IIFE (immediately invoked function expression). So, the IIFE calls itself and returns an anonymous function which is finally assigned to updateClickCount.

Now, this anonymous function forms a closure with the parent function so that it has access to the parent function's variables i.e. counter and p.

When we click, it calls the updateClickCount which references to the anonymous function, increments the counter and updates the textContent of p.

Well, this is it from my side. See you soon 😁

Top comments (2)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Good post.

Collapse
 
abhishekjain35 profile image
Abhishek Jain

Thanks for reading Andrew. 😄😄