4

By mistake, I wrote:

++number++;

and got this:

Uncaught ReferenceError: Invalid left-hand side expression in prefix operation

Why? I would except this to to first increment number by one and then increment number by one again.

gsamaras
  • 71,951
  • 46
  • 188
  • 305

1 Answers1

9

In JavaScript, ++ is both the prefix and postfix increment operator. The postfix operator has higher precedence, and so when we apply precedence, your expression becomes:

++(number++);

The result of number++ is a value, not a variable reference, and so it cannot be the operand of the prefix increment operator, for the same reason ++42 is invalid — there's nowhere to write the result back to.


Why does it call it the "left-hand side expression" when it's to the right of the operator? You'd have to look at the V8 source code (I can tell from the text of the error you're doing this on V8, probably Chrome). I can speculate that it's because many operators accept two operands (left and right), and that they just call the only operand to unary operators like ++ the "left-hand" by default. But that's speculation.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    I must wait 9 minutes to accept the answer, as you know. I didn't know that. Especially that the postfix has greater precedence over the prefix, it's something I didn't expect! Thanks T.J.! Yes, I am in Chrome! – gsamaras Sep 26 '15 at 09:59
  • 1
    @gsamaras: I have to admit I had to look the precedence up. :-) I knew what the basic issue was, but not which had higher precedence. [MDN to the rescue](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) (since figuring out precedence from the specification itself is...awkward). MDN isn't always correct, but it has a good solid record. – T.J. Crowder Sep 26 '15 at 10:01