0
function setupCounter(val){
  console.log(val);
    return function counter(){
      console.log('counter func ', val);
        return val++;
      }
    }
debugger
let counter1 = setupCounter(0);
console.log(counter1()); //0
console.log(counter1()); //1

Why the first counter1() does not increment value and returns 0. But the second call increments the value to 1, as expected: here is what I've been debuggin

Aziza Kasenova
  • 1,501
  • 2
  • 10
  • 22
Mekkush
  • 5
  • 4
  • Use `return ++val` – Keith Jul 01 '21 at 16:11
  • 1
    val++ vs ++val I think is what you are confused about? val++ returns the value first, then increments it - while ++val increments the value first then returns it. if you are expecting (0) to return with a 1 - then you need to increment it first then return it. – altruios Jul 01 '21 at 16:11
  • And ideally you would get 2 in second case, 1 in first case because of closures. – Tushar Shahi Jul 01 '21 at 16:18

1 Answers1

4

The issue here is the postfix increment operator doesn't return what you expect. Quoting from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment:

If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.

If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.

Using val++ will actually return the previous value, rather than what it becomes. If you want it to return the new value, you'd use the increment operator as a prefix, like: ++val.

Because of this common confusion, I prefer to be more verbose and do something like this:

val += 1;
return val;
johnpyp
  • 867
  • 2
  • 7
  • 13