What is closure in JavaScript?

A closure in JavaScript is created when a function “remembers” the variables that were in the surrounding code when it was created.

Imagine you have a house with a garden. Inside the house, you have a room with a secret code that only you know. You invite a friend over and take them to the garden. While in the garden, you tell them the secret code that unlocks the room. Even though you’re no longer in the room, your friend can still use the code to access the room because they have “closure” over the secret code.

In the same way, a function in JavaScript can “remember” variables that were in the surrounding code when it was created. Even if the function is called later and the surrounding code is no longer in scope, the function can still use the remembered variables.

Closures are useful for creating functions that can access private data. Just like the secret code in the house, the remembered variables are not accessible to anyone else but the function that has “closure” over them.

However, it’s important to be mindful of potential memory leaks when using closures. If a function with a closure is not properly handled, it can prevent the garbage collector from freeing up memory. So, like the secret code in the house, it’s important to use closures responsibly.

Here is an example of counter which uses closure:

var counter = (function () {
  var _count = 0;
  return function () {
    _count++;
    console.log(_count);
  };
})();

counter(); // Output: 1
counter(); // Output: 2
counter(); // Output: 3
counter(); // Output: 4
counter(); // Output: 5

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: