The Exponentiation Operator
The only change to JavaScript syntax introduced in ECMAScript 2016 is the exponentiation operator, which is a mathematical operation that applies an exponent to a base. JavaScript already had the Math.pow()
method to perform exponentiation, but JavaScript was also one of the only languages that required a method rather than a formal operator. (And some developers argue an operator is easier to read and reason about.)
The exponentiation operator is two asterisks (**
) where the left operand is the base and the right operand is the exponent. For example:
let result = 5 ** 2;
console.log(result); // 25
console.log(result === Math.pow(5, 2)); // true
This example calculates 5^2^, which is equal to 25. You can still use Math.pow()
to achieve the same result.
Order of Operations
The exponentiation operator has the highest precedence of all binary operators in JavaScript (unary operators have higher precedence than **
). That means it is applied first to any compound operation, as in this example:
let result = 2 * 5 ** 2;
console.log(result); // 50
The calculation of 5^2^ happens first. The resulting value is then multiplied by 2 for a final result of 50.
Operand Restriction
The exponentiation operator does have a somewhat unusual restriction that isn’t present for other operators. The left side of an exponentiation operation cannot be a unary expression other than ++
or --
. For example, this is invalid syntax:
// syntax error
let result = -5 ** 2;
The -5
in this example is a syntax error because the order of operations is ambiguous. Does the -
apply just to 5
or the result of the 5 ** 2
expression? Disallowing unary expressions on the left side of the exponentiation operator eliminates that ambiguity. In order to clearly specify intent, you need to include parentheses either around -5
or around 5 ** 2
as follows:
// ok
let result1 = -(5 ** 2); // equal to -25
// also ok
let result2 = (-5) ** 2; // equal to 25
If you put the parentheses around the expression, the -
is applied to the whole thing. When the parentheses surround -5
, it’s clear that you want to raise -5 to the second power.
You don’t need parentheses to use ++
and --
on the left side of the exponentiation operator because both operators have clearly-defined behavior on their operands. A prefix ++
or --
changes the operand before any other operations take place, and the postfix versions don’t apply any changes until after the entire expression has been evaluated. Both use cases are safe on the left side of this operator, as this code demonstrates:
let num1 = 2,
num2 = 2;
console.log(++num1 ** 2); // 9
console.log(num1); // 3
console.log(num2-- ** 2); // 4
console.log(num2); // 1
In this example, num1
is incremented before the exponentiation operator is applied, so num1
becomes 3 and the result of the operation is 9. For num2
, the value remains 2 for the exponentiation operation and then is decremented to 1.