I would like to ask you a question about the difference "between calling a function" with "storing the same function in a variable and then calling it".
This is a simple counter function with closure.
function makeCounter() {
var count = 0;
function counter() {
count = count + 1;
return count;
}
return counter;
}
var doCount = makeCounter();
console.log(doCount());
console.log(doCount());
console.log(doCount());
console.log(makeCounter());
console.log(makeCounter());
console.log(makeCounter());
And when we use our counter like this:
console.log(doCount());
console.log(doCount());
console.log(doCount());
The Output is:
1
2
3
But when we call the function like this:
console.log(makeCounter());
The output look like this:
[Function: counter]
[Function: counter]
[Function: counter]
What is going on under the hood? Please explain. Thanks.