Why is -1**2 a syntax error in JavaScript?

Solution 1:

Executing it in the browser console says SyntaxError: Unexpected token **.

Because that's the spec. Designed that way to avoid confusion about whether it's the square of the negation of one (i.e. (-1) ** 2), or the negation of the square of one (i.e. -(1 ** 2)). This design was the result of extensive discussion of operator precedence, and examination of how this is handled in other languages, and finally the decision was made to avoid unexpected behavior by making this a syntax error.

Solution 2:

From the documentation on MDN:

In JavaScript, it is impossible to write an ambiguous exponentiation expression, i.e. you cannot put a unary operator (+/-/~/!/delete/void/typeof) immediately before the base number.

The reason is also explained in that same text:

In most languages like PHP and Python and others that have an exponentiation operator (typically ^ or **), the exponentiation operator is defined to have a higher precedence than unary operators such as unary + and unary -, but there are a few exceptions. For example, in Bash the ** operator is defined to have a lower precedence than unary operators.

So to avoid confusion it was decided that the code must remove the ambiguity and explicitly put the parentheses:

(-1)**2

or:

-(1**2) 

As a side note, the binary - is not treated that way -- having lower precedence -- and so the last expression has the same result as this valid expression:

0-1**2

Exponentiation Precedence in Other Programming Languages

As already affirmed in above quote, most programming languages that have an infix exponentiation operator, give a higher precedence to that operator than to the unary minus.

Here are some other examples of programming languages that give a higher precedence to the unary minus operator:

  • bc
  • VBScript
  • AppleScript
  • COBOL
  • Rexx
  • Orc