2

I was going through a JS tutorial, and came across this example:

function makeCounter() {
  function counter() {
    return counter.count++;
  };
  counter.count = 0;

  return counter;
}

let counter = makeCounter();
counter.count = 10;
console.log(counter()) // logs 10

What I don't understand is why it didn't log 11 instead of 10? If we have set the count property to 10 and stored the function counter that increments count property, why the property is not incremented then to 11?

Leff
  • 1,968
  • 24
  • 97
  • 201

3 Answers3

3

You understand the function property well. This has to do with how ++ works.

return counter.count++; will return counter.count at its current value, THEN increment it, not the other way around.

Hugo Migneron
  • 4,867
  • 1
  • 32
  • 52
0

Cause you are using the postfix increase operator, which firstly returns its current value, then it increases it. You could change that to a prefix increase:

   return ++counter.count;
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
-1

Your function makeCounter is returning a function, which has access to the [[scope]] . It's using closure. so It is obvious it works like that.

Closure : ' When a function memorizes the data from the place where he was called from' .

Further information ; What is a 'Closure'?

Atlas
  • 241
  • 3
  • 19