I'm studying for an exam on JavaScript at the moment. I've also got a little knowledge of C and Perl so I'm familiar with prefix and postfix notation in all three languages.
I did an online practice exam for it and one mistake I made was in evaluating the following code:
var x = 10;
x += x--;
Now, I thought it would evaluate to 19 because it would be 10 + 10, then subtract 1 to make 9. But the feedback I got was that it was wrong and it actually evaluates to 20. I thought that sounded a bit suspicious so I tested it out in an HTML document, and it came out with 20 again. I then tried the equivalents in C and Perl and both evaluated to 19.
Can anyone explain to me why JavaScript evaluates the answer as 20 when other languages evaluate it to 19? The answer I got from the test wasn't too clear to me:
The increment ++ and decrement -- operators can be placed either before or after an operand. If the increment or decrement operator is placed before the operand, the operation occurs immediately. If the increment or decrement operator is placed after the operand, the change in the operand's value is not apparent until the next time the operand is accessed in the program. Thus the expression x += x-- is equivalent to x = x + 10 which evaluates to 20.