Why is JavaScript's post-increment operator different from C and Perl?

Expanding the statement

x += x--;

to the more verbose JS code

x = x + (function(){ var tmp = x; x = x - 1; return tmp; })();

the result makes perfect sense, as it will evaluate to

x = 10 + (function(){ var tmp = 10; x = 10 - 1; return tmp; })();

which is 20. Keep in mind that JS evaluates expressions left-to-right, including compound assignments, ie the value of x is cached before executing x--.


You could also think of it this way: Assuming left-to-right evaluation order, JS parses the assignment as

x := x + x--

whereas Perl will use

x := x-- + x

I don't see any convincing arguments for or against either choice, so it's just bad luck that different languages behave differently.


In C/C++, every variable can only be changed once in every statement (I think the exact terminology is: only once between two code points, but I'm not sure).

If you write

x += x--;

you are changing the value of x twice:

  • you are decrementing x using the postfix -- operator
  • you are setting the value of x using the assignment

Although you can write this and the compiler won't complain about it (not sure, you may want to check the different warning levels), the outcome is undefined and can be different in every compiler.

Tags:

Javascript

C

Perl