So I was fooling around with the new exponentiation operator and I discovered you cannot put a unary operator immediately before the base number.
let result = -2 ** 2; // syntax error
let result = -(2 ** 2); // -4
let x = 3;
let result = --x ** 2; // 4
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.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.
I understand this was made an error by design. I don't understand this design decision. Who's really going to be surprised that -x ** 2
is negative? This follows not only other mainstream programming languages but a mathematical notation that has been in common use for hundreds of years and is taught to every high school algebra student.
In Javascript '1'+ 2
is '12'
and '1'-2
is -1
but -1**2
raises an error because it could be ambiguous? Help me understand this design decision.
-x ** 2
instead of- x**2
would make it ambiguous alone. – Vagabond-1²
is-1
. It's-(1²)
, not(-1)²
. I went 'round and 'round in my head on that one and finally punted and asked the question. It's been that long since math class. But I'm also a bit embarrassed to have asked, since I routinely see things like-2³² + 1
and have no trouble interpreting that correctly (2³² = 4294967296, -4294967296 + 1 is -4294967295). – Hispaniola