UI Development

Closures

Javascript is a functional-oriented language. It allows us to create functions, pass them as variables, copied to another variable. Terms like “Closures” may make Javascript appear mystical. But in-reality you’ve probably used the mystery without knowing it.

What is a closure?

“Closure means that an inner function always has access to the parameters of its outer function, even after the outer function has returned”.

Let me support this statement with a simple example

In the above code we have 2 functions, outerFunction and innerFunction.

  • outerFunction contains a variable learn. It also has an-other function within it named innerFunction
  • Inner Function here is a function inside the outerFunction, which has access to the variable “learn” declared in the outerFunction.

In line 8, we are calling the outerFunction and storing its result in variable a.

During the execution phase of the outerFunction, the variable learn contains “Closure”. Line 3-5 are not executed since it’s a function declaration. Since we are returning a function (entire body) in line 6, the variable “a” contains the returned value which is innerFunction.

outerFunction() finishes the execution and all the variables within the scope of this function no longer exist.  Once a function completes its execution, variables declared inside the function scope tend to exit.

Now to invoke the returned function, we simply call it by – ( ). Line 9, a() executes the inner function.

The inner function has only one logging statement (Line 4), when this line in executed, since “learn” is part of the outerFunction and the execution of the outerFunction has been completed and the variable inside them have cease to exist, “learn” variable doesn’t exist.

How is this handled ?

With Javascript closures the inner function can have access to the variables of the enclosing function.

Which means, the inner function stores the scope of the enclosing function even after the outerFunction has completed its execution.

In our example, learn = “Closures” has been stored by the innerFunction.  Which in turn gives us the result.

//Output :  I’m understanding Closures.

Let’s try to take a scenario to learn advantages of Closures.

Requirement: Build a voting application, which helps us in recording the votes. And see the results.

Imagine Dog, Cat and dolphin are contesting for the best pet award. WAP to register their votes and view the results.

A simple code is written to the votes in random for the 3 contestants. The for loop in line 29 randomly distributes the votes to all the contestants.

When we see the result of this program, you see the votes distributed randomly between dogs, cats and dolphins.

Output:

This is just a normal JS program which randomly distributes votes to 3 contestants. Now imagine somebody who is so inclined towards a particular contestant, i.e Dogs here. He would like to do some election manipulation or vote rigging to make sure dogs win.

In order to achieve this, he waits until the voting is done (line 34)  and tries manipulating the votes by adding the below code.


Output:

This would over all affect the voting system, like shown below

So how do we overcome this, how do you stop somebody from affecting the votes of the contestants.

This is where CLOSURES come handy, let’s rewrite the program using the closures concept.

Output:

We create a new dogsInterface, an IIFE, which sets the votes to 0 initially and return the functions inside them, increment and showStats functions. Increment function would add up to the votes and showStats function would log total number of votes registered under dogs.

You can clearly see that the votes are increasing when we are calling the showStats.

This works on the concept of closures, even after the outer function is returned, we have access to its parameters from the inside function, in our case we have access to votes even after the dogsInterface has returned the functions (increment and showStats, line 15).

Let’s rewrite the complete program using this concept now.

Output:

Since the votes are declared in private, ie inside the respective functions and are not exposed we cannot tamper the votes, which solves the basic problem of rigging.

Summary :

If anything seems unclear, playing around it would help us understand it better

  • A closure is created every time a function is declared.
  • A classic example of a closure is, returning a function from inside another function. Since the state is available to the inner function even after execution of outer function.

Closures are not hard to understand once the main concept is understood. However, you face difficulties to understand by reading any theoretical or academically related explanations!

About The Author