johnao johnao -3 years ago 93
Javascript Question

JavaScript increment (++) operator on both sides of an argument?

I'm struggling to understand the behaviour of Javascript's increment operator, and more specifically, why certain cases fail.

Why does adding increment operator on both sides of an argument fail?

EXAMPLE:

let a = 1;
++a++;


This returns a horrible error stating that:

ReferenceError: Invalid left-hand side expression in prefix operation


What does this mean, and should I be worried?

Answer Source

The increment operators work on variables, not on expressions. You can't increment a numeric expression:

3++ // Uncaught ReferenceError: Invalid left-hand side expression in postfix operation

The reason for this is that it must increment the value, then save it back to the variable. If you gave it any old numeric expression, what would it assign the result to?

One of the two operators will work, but it returns the result of the operation, which is an expression, not a variable:

++(a++)

The first operator, a++, will increment a, and return the result: 2. The second operator is then trying to perform the increment on the value 2, which is invalid syntax.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download