Hi,
So i was thinking well now i have a good idea of what closure is, just an inner function having access to values of the outer function kept alive …
Now i came across a simple exercise, keep the value of a variable incremented by one each time a function is called , i tried …Every time the value is 0 or 1, is there no way to achieve it with out some super complex closure , … they are asking me to try some thing like this — But i have no clue why this works and others do not, so is there no other way to achieve this with out closures? Kindly guide
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
WORKS
function add() {
var counter = 0;
function plus() {
counter++;
}
plus();
return counter;
}
FAILED
function add() {
var counter = 0;
function plus() {
counter++;
}
plus();
return counter;
}
FAILED
function add() {
var counter = 0;
counter++;
return counter;
}
FAILED
PS - In the end all is want is increment the value of a variable each time a function is called