Closure is the heart of  functional programming world. Yes now C++, Java , Ruby, Python etc all have closure concept which we can say are actually inspired by Javascript! .

Now let us see How this Javascript got closure concept?

Brenden Eich the designer of Javascript actually wanted to use Scheme Programming language in browser as he loved the concepts used by this language and one of them was Closure.

As Netscape did not want to use Scheme in browser.

Netscape advised Brenden to design a language that somewhat looks like Java and has concepts of Scheme.

Then an amazing Multi-paradigm, object-oriented (prototype-based), imperative, functional, event-driven programming language called JAVASCRIPT took birth.

Closure Definition :

Closure is a function which remembers the variables around it even that function is executed anywhere (outside of the lexical scope).

OR

Closure is function which carries a backpack of variables around it even when it is executed anywhere(outside of the lexical scope).

First example:

function add(a, b) {

    var sum;

    return function() {

        if (sum === undefined) {

            // when x() is called for the first time the sum will be undefined and sum=a+b statement will execute.

            sum = a + b;

        }

        return sum;

    }

}

var x = add(5, 2);

x(); // 7

x(); // 7

you may be thinking why this sum stores the value and for the second time sum is not undefined?! That is the power of closure where it is keeping the memory around the function.

let us try to understand with another example:

function increment() {

    var i = 0;

    return function() {

        return i++;

    }

}



var x = increment();



x(); // 0

x(); // 1

x(); // 2

 

Oh! again you may be thinking how does that second, third call returning the values 1 and 2.

Let us understand this example step by step:

Remember we are actually returning the inner function and  var i =0 is executed only once when we have executed var x=increment()


x has the inner function as the reference.


calling x() will return 0 (Again do not get confused we are using the post-increment here so the first call will return 0 if you use pre-increment guess what? It will be 1)


calling x() will return 1 (There comes the power of closure as it stores the value changed before)


calling x() will return 2 ( As the previous value is 2 which was stored)

 

Looking for ReactJS Development Company, Hire our dedicated developers!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.