1

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?

John
  • 549
  • 4
  • 12
  • 4
    Why are you using this?? – Derek Pollard Jun 14 '17 at 19:46
  • You're getting this error because of ++a. The correct syntax is a++. I am not sure what you're trying to achieve with ++a. Can you elaborate on that? – jonode Jun 14 '17 at 19:47
  • 1
    I'm trying to think of a case where this would be necessary or useful and coming up short – j08691 Jun 14 '17 at 19:48
  • 4
    @jonode `++a` is perfectly [valid](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()). "If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing." – j08691 Jun 14 '17 at 19:48
  • @j08691 Wow, I have honestly never seen that. So maybe he's trying to increment by 2? So a+=2? – jonode Jun 14 '17 at 19:49
  • 2
    **DISCLAIMER**: I'm not actually using it, I'm just curious as to why it doesn't work. – John Jun 14 '17 at 19:49
  • This may be a useful resource for you. https://stackoverflow.com/questions/971312/why-avoid-increment-and-decrement-operators-in-javascript Cheers! – Zander Y Jun 14 '17 at 19:50
  • It fails because it's invalid syntax. just like `a = 5 /////////////// 7` or `a = purple monkey dishwasher ocelot` – Dave S Jun 14 '17 at 19:51

2 Answers2

10

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.

Andrew Williamson
  • 8,299
  • 3
  • 34
  • 62
4

That code could be rewritten as: ++(a++) which would translate to ++(1), and then ++1, which is not a valid expression.

Juan Tonina
  • 549
  • 9
  • 15