I have the following two counter functions which return different result when they run.
In the first snippet, counter function is assigned to variable letsCount and it looks like executing the function updates the var count in the counter function.
However in the second snippet, executing the function directly doesn't update the count variable.
Would you please explain why they have different results and what happens when the function that returns function is assigned to a variable?
Snippet 1
function counter() {
var count = 0;
return function() {
console.log(count++);
}
}
var letsCount = counter();
letsCount(); // 0
letsCount(); // 1
letsCount(); // 2
Snippet 2
function counter() {
var count = 0;
return function() {
console.log(count++);
}
}
counter()(); // 0
counter()(); // 0
counter()(); // 0
Every time you call counter() you create a new anonymous function instance, with its own scoped variables. If you want to keep using the same function, you will have to do something like this :
var counter = (function () {
var count = 0;
var fn = function() {
console.log(count++);
};
return function () {
return fn;
};
})();
counter()(); // 0
counter()(); // 1
counter()(); // 2
A single anonymous function will be created then stored in a scoped fn function, then we return a function which, when called, will returns the value kept by fn.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With