-2

when i use ++ operator in javascript, why I get the value at last is 100 not 101? I want to know the detail of the ++ operator in javascript?

let value = 100;
value = value++;
console.log(value); // 100 why the value is 100 at last
Kirto
  • 1
  • 2

2 Answers2

0

Because when you have the assignment operator, the right-hand operand is evaluated first, then that value is assigned to the receiver on the left.¹

So here's what happens in value = value++:

  1. Read the value of value (100) and set it aside (since we'll need it in a minute).
  2. Increase the value of value by one (making it 101).
  3. Take the value from #1 (100) as the result value of the right-hand operand.
  4. Store that value in value.

¹ In specification terms it's slightly more complicated than that, but the details aren't important here.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    There **has** to be a dupetarget for this, hence the CW. (I find that if I go hunting first, poor answers pile up...) – T.J. Crowder Dec 11 '21 at 15:08
  • I can't actually find one that handles the assignment part (and don't want to spend more time looking). The two marked questions don't handle that part, but they do explain postfix increment, so...meh, close enough. – T.J. Crowder Dec 11 '21 at 15:11
0

That's because <value>++ returns the previous value and not the new one If you want it to return the new value use ++<value>

xoriwi
  • 11
  • 1