1

Today I see a weird result with the postfix and assignment operator which I was not expecting at all.

let say

let a = 10;

when we increment with postfix, it will result with the addition of 1 as follows

console.log( a++ );    // 10
console.log( a );      // 11

AFAIK a++ is a postfix operation which means

  • First, it will use the value(that's why a++ returns 10) and then
  • update the value
  • When we print the value, the value has been updated. That's why a returns 11.

So far so good,

But when I assigned the postfix operation to a variable, it won't update the value.

a = a++;
console.log( a );     // 11  

Though I was expecting the result to be 12. Why this result? Thanks in advance.

let a = 10;
console.log(a++);
console.log(a);

a = a++;
console.log(a);
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • 1
    I thought maybe it would be because of the precedence of the `assignment` or `postfix` operator. But the precedence of `postfix` is greater than `assignment`. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence – DecPK Mar 09 '21 at 03:52
  • 2
    `a++` evaluates to the value of `a`, then increments `a`. The original value of `a` is being re-assigned back to the variable after the increment occurs (because that is what the postfix expression evaluated to) –  Mar 09 '21 at 03:55
  • that means `b = b` and `b = b++` are both equal. – DecPK Mar 09 '21 at 04:00
  • Yes, that is what the postfix operator does. –  Mar 09 '21 at 04:04
  • @SebastianSimon yeah this answer my question – DecPK Mar 09 '21 at 17:31

1 Answers1

1

It does increment but if you breakdown the process,

Since the precedence of the postfix is greater than assignment

b = b++

Step 1 => Execute b++ which returns b

Step 2 => Assign returned value to the b, i.e assign b to b

Now console.log show the same old value.

b = 10;

Step 1 => return 10 and increment to 11. Step 2 => Since the returned value is 10, re assign the 10 to a which cause console.log(a) to show 10 as the value.

Dilshan
  • 2,797
  • 1
  • 8
  • 26