0

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.

  • over here in `console.log(doCount())` your `counter()` function is actually called but in case of `console.log(makeCounter());` you are not calling `counter()` function as you are returning `return counter` not `return counter()`. – Gaurav Gupta Mar 11 '21 at 15:44
  • But when I return `return counter()` The output is always: 1. This is not what I expected. The output should be 1 2 3 and so on. – shivam biswas Mar 11 '21 at 15:51
  • Yes, that is expected because if you return `counter()` your count variable is not updated but in the case of return `counter` you update the count variable. It is because in the first case doCount get value from makeCounter() separately every time and in the second case makeCounter() is called once and counter is called 3 times which updated count variable. – Gaurav Gupta Mar 11 '21 at 16:00

0 Answers0