Explanation of JavaScript Closures

Explanation of JavaScript Closures

Table of contents

No heading

No headings in the article.

What are Closures?

A closure is a combination of a function bundled together with relations to its surrounding state (the lexical environment).

In simple words, every function in Javascript has access to its outer lexical environment(variables, functions) which is present inside the environment of the parent. Even when this function is executed in some other scope, it still remembers its outer lexical environment from where it was originally present in the scope.

Now let's see an example for better understanding!

function outer(){
    var name="Ranita";
    function inner(){
        console.log(name);
    }
    return inner;
}

var myFunc=outer();
console.log(myFunc); // function:inner
myFunc(); //Ranita

Here, when myFunc is invoked, the inner function is returned. So, when we finally invoke myFunc, inner is invoked. Now the inner has to do log name. So,

  • At first, it tries to find it in the local memory but it's not there.

  • It then goes to its parent function. In this example, it goes to the outer.

The closure is the most esoteric of JavaScript concepts. It enables powerful pro-level functions like ‘once’ and ‘memoize’

Let's see another example:

function outer (){
    let counter = 0;
    function incrementCounter (){ 
        counter ++; 
        console.log(counter);
    }
    return incrementCounter;
   }

   const myNewFunction = outer(); //Reference to incrementCounter which is global
   myNewFunction(); // 1
   myNewFunction(); // 2

   // Reference to modified counter variable in scope of incrementCounter
   const myFunction = myNewFunction;
   myFunction(); // 3
   myFunction(); // 4

// Even if we increment the counter value, which has the reference from outer(),but it's in another scope
   const anotherFunction = outer();
   anotherFunction(); // 1
   anotherFunction(); // 2

This whole concept is called Closure which is also called as P.L.S.R.D. which stands for: P-Persistent, L-Lexical, S-Scope, R-Referenced, D-Data

In this example, when we're invoking anotherFunction, we're getting values 1 and 2 and not 5 and 6. This is because anotherFunction is a whole new copy of the outer function and it won't impact the output of myFunction.

Advantages of Closure:

  1. Module Design Pattern
  2. Currying
  3. Memoize
  4. Data hiding and encapsulation
  5. setTimeouts etc.

Disadvantages of Closure:

  1. Overconsumption of memory
  2. Memory Leak
  3. Freeze browser

So, the key points to remember always.

The closure has three scope chains:-

  1. Access to its own scope.
  2. Access to the variables of the outer function.
  3. Access to the global variables.

That's it, thanks for making it to the end, hope you learned something interesting. Let's connect on Twitter or LinkedIn

Have a great day! :)