Friday, April 10, 2020
Home Javascript Understand JavaScript Closure in Five minutes

Understand JavaScript Closure in Five minutes

Author

Date

Category

Function, Subroutine, Sub procedure and Methods all looks same. Very confused already…. Again now one more “Closure”. What is a closure ?

What is a Closure?

closure is a function, whose return value depends on the value of one or more variables declared outside this function.
var b = 10;
function inner() 
{
  var a = 20; 
  var z=a+b;
  return z;
}

In the above code the function inner has one local variable “a” and one global variable “b”. The inner function returns “z” which depends on “b”. This types of functions are specifically called as “closure”. But we have used this type of function many times in our code without thinking it so seriously, then why now we are learning this and given a special name to this type of function as “Closure”.

The reason is when we are writing a program using language which supports the concept of First-Class-Function then a small but very critical problem occurs and that gives birth to Closure.
But wait…. What is First Class function then ?

A programming language is said to have First class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functionscan be returned by another function and can be assigned as a value to a variable.

This is the beauty of functional programming that any function can be assigned to a variable as a value and also can be returned from another function as well. This concept can get more clarity if we see one example.

In javascript: This is functional Programming

var foo = function() {
	var test = "Hello";
	var bar = function() {
		console.log("Hi");
	}
	return bar;
}
 
foobar = foo();
foobar();
OUTPUT:
"Hello, World!"

In the above code one anonymous function has been assigned to the variable foo. The same function has two variables and one variable “test” has a string value assigned to it where as other variable “bar” has a function assigned to it. The anonymous function returns “bar” variable which actually refers to a function.

“foobar” variable hold the return value from the foo(). Remember “foo” is a variable but treated as a function as it is assigned a function to itself. Now the “foobar” is having the value of the “bar” variable to it which is again a function. So “foobar” also need to be used as function.

foobar() is invoked then actually value of the bar variable is invoked which is a function.

Use of function in this way (assigning function to variable and returning function from another function) is not easily achievable in C#.

Get back to closure again…….

A small modification in the code has been done now. We can see in the below code that the variable “bar” is dependant on “test” variable which was not the case in the last section. This is the special circumstance where the function become hero with support of closure. But what is the problem in the code ? Please find.

var foo = function() {
	var test = "Hello";
	var bar = function() {
		console.log(test+"Niladri);
	}
	return bar;
}
 
foobar = foo();
foobar();

In the absence of special care and in normal circumstances what supposed to happen?

1. In the first time execution foo() is called.
2. Value of the “test” variable is assigned.
3. Value of the “bar” variable is assigned but the function assigned to the “bar” is not executed as bar(); is never called.
4. The value of the variable “bar” is returned and assigned to “foobar” variable.
5. Scope of the foo() is expired and variable “test” is also expired. Only value of the “bar” variable is stored in foobar.
6. Now calling the foobar() means we are calling the

function() {
console.log(test+”Niladri);
}

But when we are calling the foobar() then how it will understand the variable “test” used inside its body. variable test is already expired. This is the problem which need to be resolved, if we want our programming language to have first-class-function support.

Closure handles this issue by storing a local copy of the variable declared outside the function which are used inside that. In more technical words

“The inner function preserves the scope chain of the enclosing function at the time the enclosing function was executed, and thus can access the enclosing function’s variables in the future case when only it executes without the execution of its enclosing function.”

Need more example? Ok one more will give clarity

function outer() {
var b = 10;
var inner = function() {
         var a = 20; 
         console.log("a= " + a + " b= " + b);
    }
   return inner;
}
var X = outer();  

When the above code will start executing:

  1. Variable “X” will invoke the outer().
  2. The outer() now starts executing and stores value 10 to “b” and another function to variable “inner” but never executes that as it is never called like inner();
  3. The value of variable “inner” is returned and assigned to variable “X” which is actually a function.
  4. Scope of the function outer() is finished now and both the values of the variables “b” and “inner” are expired and not accessible.

Now what will happen if we call function X()

Because X stores the return of outer() and outer() returns variable “inner” which stores a function. So finally “X” is a function.

Now calling X() is same as calling

function() {
          var a = 20; 
          console.log("a= " + a + " b= " + b);
     }

But variable “b” in this code is already expired. So this will cause error in any language which does not support Closure. But who support Closure like JS & Scala will not throw error instead will render perfectly. As Closure preserves the values of the outer variables in local scope and the entire scope chain is stored locally. So the function call X(); will render as

Output:

a=20 b=10

Closure is added in JAVA 8. If any one tried then please let share your experience here.
Article on Implementation of closure in Scala is coming Soon.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subscribe to our newsletter

Niladri Bihari Mohanty
I am a Scientist-C at National Informatics Center. I am a hard core programmer with absolutely no sticky relationship with any specific language.

Recent posts

Recent comments