What is a closure?

If you can't explain it to a six-year old, you really don't understand it yourself.

In obligation with the above words, I want to make this important concept very easy and crystal clear in a way, 6 year old are doing, in 5 minutes.

Scenario:

We have to write a method to write any "Number table" which will increment the table output with every call uniquely (uses of closure).

every call

uniquely

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

//for table 2

var tableMaker2 = tableMaker(2);

tableMaker2() -> output 2;

tableMaker2() -> output 4;

tableMaker2() -> output 6;

//for table 5

var tableMaker5 = tableMaker(5);

tableMaker5() -> output 5;

tableMaker5() -> output 10;

tableMaker5() -> output 15;

//both table method should work independently

tableMaker2() -> output 8;

tableMaker5() -> output 20;

tableMaker2() -> output 10;

tableMaker2() -> output 12;

tableMaker5() -> output 25;

Implementation without closure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

//main scope

{

var t=1;

var t1=1; // for table 5 method and so on

var tableMaker2 = function(var x){

console.log(x*t++) // for x=2, output will be 2*1 next call 2*2 ...

};

//printing

tableMaker2(2);//2

tableMaker2(2);//4 and so on

//NOTE: we are cluttering the main scope with variable t and t1 etc.

}

Implementation with closure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

{//main scope

var tableMaker= function(x)

{

var t = 1;

return function(){

console.log(x*t++);

};

}//outer function

}

//for table 2

var tableMaker2 = tableMaker(2);

tableMaker2 () -> output 2;

tableMaker2 () -> output 4;

//for table 5

var tableMaker5 = tableMaker(5);

tableMaker5 () -> output 5;

tableMaker5 () -> output 10;

//both table method closures are working independently with their own context.

tableMaker2 () -> output 8;

tableMaker5 () -> output 20;

}//main scope

Definition:Now the tbl2 and tbl5 variables have a a complete context of what the function is and what are the variables it depends on, in this case x and t for the inner function are also included in their context.

1
2
3
4
5
6
7
8
9
10

tbl2 = {

var t = 1; //x=2 from the outer function parameters

return function(){

console.log(x*t++);

};

tbl5 = {

var t = 1; //x=5

return function(){

console.log(x*t++);

};

A "closure" is a function that can have variables bound with it, together with its environment that binds those variables.