I am currently studying the JavaScript exam. I also gained a little knowledge of C and Perl, so I am familiar with the prefix and postfix notation in all three languages.
I did an online exam for this, and one mistake I made was to evaluate the following code:
var x = 10; x += x--;
Now I thought that he would evaluate to 19, because it would be 10 + 10, and then subtract 1 to make 9. But the feedback I received was that it was wrong, and in fact it rated to 20. I thought this sounds a little suspicious, so I tested it in an HTML document and it came out with 20 again. Then I tried equivalents in C and Perl, and both were rated as 19.
Can someone explain to me why JavaScript rates the answer as 20 when other languages rate it as 19? The answer I received from the test was not too clear:
++ increment and decrement - operators can be placed either before or after the operand. If an increment or decrement operator is placed before the operand, the operation is performed immediately. If the increment or decrement operand is placed after the operand, changing the value of the operand is not obvious until the next operand is available in the program. Thus, the expression x + = x-- is equivalent to x = x + 10, which evaluates to 20.
javascript postfix-notation
Matthew daly
source share