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
counter, you create a new function and setcountto0.