Why does +++ x give an error when + x ++ works fine?

var x = null; 

+++x throws a ReferenceError , but when I do the same with the postfix +x++ increment operator, it works fine.

+7
source share
3 answers

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

 1++; 

will fail with the same error (invalid increment operand). You can only use pre- and postincrement statements for variables / identifiers / expressions.

Since the + sign distinguishes null value from the number (0), you get the same result.

Examples:

 var foo = null, bar = 5; foo++; // 0 0++; // invalid increment operand null++; // invalid increment operand (+bar)++ // invalid increment operand foo++ +2; // 2 
+5
source

+ x ++ is divided into two stages:

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

+++ x is also divided into two steps, but in a specific order:

  • ++ x is evaluated first, which throws an exception, since x is null.
  • + x will then be evaluated, except that you already have an exception.

I think your assumption was that +++ x would be parsed as ++ (+ x), but it would actually be parsed as + (++ x). This is an ambiguous syntax, the language developers had to choose one of two ways to parse it, and from your point of view they chose the "other".

Honestly, there is absolutely no value in formatting your code anyway - all you get is dubious code that is designed to confuse people.

+1
source

if u uses x = 0; x will be initialized with the integer type, which the operator ++ x will accept, while ++ (+ x) as ++ (+ null) so it’s better to try switching to X = 0;

0
source

All Articles