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

JavascriptExponentiationEcmascript 2016

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

> 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 - Javascript

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:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpsmithView Question on Stackoverflow
Solution 1 - Javascriptuser663031View Answer on Stackoverflow
Solution 2 - JavascripttrincotView Answer on Stackoverflow