Javascript : Closure with simple examples!

Sasicronj
2 min readFeb 23, 2021

Now let us see How this Javascript got closure concept?

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

Netscape did not want to use Scheme in the 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(); // 7x(); // 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(); // 0x(); // 1x(); // 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)

Be it a software developer, programmer, coder, or a consultant, CronJ has it all. CronJ has been a trustworthy company for startups, small companies, and large enterprises. Hire the web of experienced React developers for your esteemed project today.

ReactJS Development Services

--

--