Wednesday, June 28, 2017

Closure in JavaScript

“…an inner function always has access to the
vars and parameters of its outer function, even
after the outer function has returned.”
-- Douglas Crockford

In Non Closure variable value will be lost once function return. And whenever it is called it will be assigned new value. Below is example of non closure.

function NonClosureFunct(){
var counter = 0;
counter += 1;
return counter;
}

Closure  help to address this problem and retain value of variable even after return from function.Variable stays around even after function returns.

function ClosureFunct(){
var counter = 0;
return function(){ counter +=1;};
}

Share:

0 comments:

Post a Comment