Search code examples
javascriptexponentiationecmascript-2016

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


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

> -1**2
...
...
...
...^C

I thought this is an arithmetic expression where ** is the power operator. There is no such issue with other operators.

Strangely, typing */ on the second line triggers the execution:

> -1**2
... */
-1**2
  ^^
SyntaxError: Unexpected token **

What is happening here?


Solution

  • 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.