-1

The output of console.log(in1()) should be 11 but it's 10 why?

function outer() {
  let i = 10;
  return function inner() {
    return i++;
  }
}

var in1 = outer();
console.log(in1());
ksav
  • 20,015
  • 6
  • 46
  • 66
  • 1
    `i++` says: when this line is over add `1` to `i`. For what you want, try `++i` instead, which is: do this now, then continue. – Tigger Dec 18 '21 at 06:32
  • Also this: [Javascript return var++](https://stackoverflow.com/questions/19262263/javascript-return-var) – aerial Dec 18 '21 at 06:52
  • And this could be the right duplicate: and this: [Why the value plus plus at last is 100?](https://stackoverflow.com/questions/70316255/why-the-value-plus-plus-at-last-is-100/70316279#70316279) – aerial Dec 18 '21 at 06:59

3 Answers3

2

Quoting https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment here:

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

Therefore, the postfix (that is, x++; postfix because it appears after) operator only gives the existing value before doing anything. That's why, when called, gives what exists, not what's the result of the addition.

Because of this, use the prefix operator instead, ++x, to get the value while still incrementing the variable.

The same applies to the decrement operator.

Justin
  • 183
  • 1
  • 1
  • 8
1

It's because using i++ returns i first, then adds 1 to i. If you call in1() the second time, you will see 11, 12 and so on. Try using ++i instead.

0

When using the postfix syntax i++ the value is returned before incrementing. Use the prefix syntax instead ++i.

Spankied
  • 1,626
  • 13
  • 21