Closures in javascript

Closures in javascript

Closures is a very important concept in javascript which you will find mentioned almost everywhere. Closures help you in achieving a wide range of features.

What is a closure?

Closure is a concept in which one function is enclosed within another function. This inner function has access to the outer functions variables and parameters. It has access to its own variables and parameters as well as the global variables. However it does not have access to the outer functions ‘this’ object and the arguments object.


Why do we need closure?

You may wonder why do we need to complicate our lives so much and have closures. Closures is a very powerful concept which can help you achieve a wide range of things.

Closures help in achieving privacy of data in the following way:

  1. You can have a set of variables defined in the outer function. Since these variables are defined within the function it will be only accessible within that function.
  2. When you define an inner function, set of variables would be accessible in the inner function due to the concept of closure.
  3. You can structure your code such that only the inner function(closure) will have accessing and updating capabilities of the outer function variables. That is you can have the inner function as getters and setters of the outer functions variables.

Closures have access to the outer functions state even after the outer function has returned.

Consider the below example:

The explanation for the above example is as follows:

  1. The ‘addition’ function is called first with value ‘5’ passed to it. This creates a closure and is stored in variable ‘addObj’. The variable addObj now has the returned closure function ‘addMore’ with value1 as ‘5’. This state is maintained even after we have exited the function
  2. When we call ‘addObj’ and pass a parameter ‘2’ to it value2 now becomes ‘2’ and the closure function ‘addMore’ is executed. Within the function addMore, value1 is ‘5’ that is maintained in the closure and value2 is the new value ‘2’ that we have passed.
  3. Now the execution takes place and addition of 5 and 2 is performed which gives the result as 7
Comments are closed.