Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does +++x gives an error message when +x++ works fine?

Tags:

javascript

var x = null;

+++x generates a ReferenceError, but when I do the same using postfix increment operator +x++, it works just fine.

like image 926
Narendra Yadala Avatar asked Oct 10 '11 16:10

Narendra Yadala


2 Answers

The LeftHandSideExpression for the ++ operator must not be a number. For instance

1++;

will fail with the same error (invalid increment operand). You can only apply the pre- and postincrement operators on variables/identifiers/expressions.

Since the + sign casts the null value into a number (0), you got the same outcome.

Examples:

var foo = null,
    bar = 5;

foo++;    // 0
0++;      // invalid increment operand
null++;   // invalid increment operand
(+bar)++  // invalid increment operand
foo++ +2; // 2
like image 197
jAndy Avatar answered Oct 12 '22 23:10

jAndy


+x++ is split into two steps:

  • +x initialises x to 0, so it's no longer null.
  • x++ then increments x, which works since x is no longer null.

+++x is also split into two steps, but in a particular order:

  • ++x is evaluated first, which throws the exception because x is null.
  • +x would then be evaluated, except you've already had an exception.

I think your assumption was that +++x would be parsed as ++(+x), but it's actually parsed as +(++x). It's an ambiguous-looking syntax, the language designers had to pick one of the two ways to parse it, and from your point of view they chose "the other one".

To be honest, there's absolutely no value in formatting your code this way anyway - all you end up with is dubious-looking code which is destined to confuse people.

like image 45
Chris Avatar answered Oct 13 '22 01:10

Chris