Why am I assigning counter function to count variable? And what is the purpose?
function counter() {
var localVar = 0;
return function() {
localVar++;
return localVar;
}
}
var count = counter(); // I am confused here.
console.log(count());
counter is a function-factory, it returns a function when called.
By assigning a variable to counter you can keep track of this counter and every time you call it the variable localVar will get incremented by one, if you were to always call counter()() you couldn't keep track of that value.
Example:
function counter() {
var localVar = 0;
return function() {
localVar++;
return localVar;
}
}
var count = counter();
for(var i = 0; i<99; i++) count();
console.log(count()); // 100
for(var i = 0; i<99; i++) counter()();
console.log(counter()()); // 1
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