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
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
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++
:
value
(100
) and set it aside (since we'll need it in a minute).value
by one (making it 101
).100
) as the result value of the right-hand operand.value
.¹ In specification terms it's slightly more complicated than that, but the details aren't important here.
That's because <value>++
returns the previous value and not the new one
If you want it to return the new value use ++<value>