Introduction
Javascript is a fantastic programming language. It has some fantastic feature and probabely one of the importent and best feature is closure.
The technical defination of closure is something like this: "When an inner function is inside in an outer function "
Then inner function has:
- Access to the variable of the outer function.
- Access to the argument of the outer function.
Sounds confusing ??? Lets try some code:
var outerfunc=function(oname)
{
return function(iname)
{
console.log(oname+" "+iname);
};
};
var one=outerfunc("Wahid");
var two=outerfunc("Faizah");
one("Khan");
two("Malisha");
So here in the above code we can clearly see there are two functions one function is inside in the another function So its a closure no doubt. The outer function name is "outerfunc" it has one argument and its return type is also a function. Actually in javascript function is a object. Sounds crazy but its true. So we can say outer function "outerfunc " have a return type of a function/object. The second function or we can say the inner function also have one argument and a console log statement.
Outside the outer function we created two functions or objects of type outerfunc with the parameter "Wahid" and "Faizah ". These two functions actually invoked the outer function with "oname" parameter. Next two line one("khan") and two("Malisha") invoked the inner function and produces the output.
In almost every other language when we reach "return" statement all the variables declare in the function will be destroyed and memory is freed up.
But in javascript when we create a closure and return from that function all the local variable will be remain in the memory and be accessible. Its a very powerful tool.
var counter=function(incnt)
{
var initcnt=incnt;
return function(val){
initcnt=initcnt+val;
console.log(initcnt);
};
};
var x=counter(4);
x(10);
x(20);
x(30);
In the above code outer fuction will be called once when we instanciate it with :
var x=counter(4);
Variable "initcnt" initilized only once when the above line execute. So when these lines executes:
x(10);
x(20);
x(30);
It always invoke the inner function. So when the x(10) execute it got the variable initcnt value 14(4+10) when x(20) execute it got the initcnt value 34(14+20) and when x(30) execute it got the initcnt value 64(34+30). So we saw that variable initcnt initilize only once.
So this is actually the closure concept.