JavaScript closures & how closures work?

Java script closures is very important topic for any JavaScript developer.
It is widely used in any JavaScript based framework.

Closures in JavaScript is an inner function in a outer function, which have access to its outer function scopes. Outer function encapsulating the data, privacy and organization using the closures.

A JavaScript closure is a pairing of:

  1. A function, and
  2. A reference to that function’s outer scope (lexical environment)

For Example:

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

add();   // 1
add();   // 2
add();   // 3

In the above example outer function ‘add’ have initial counter variable. and its returning the incremented counter.

if you call add() first time its returning the 1 after increment.

Second time add() return 2 , third time add() return 3.

Here let counter = 0; is not resetting the variable again and again. as the scope is keeping the previous state of the variable counter.

Similar Posts