The exponentiation operator (**
) will return the first operand’s power of the second operand.
a ** b is equivalent to , which is equivalent to
Math.pow(a, b)
console.log(10 ** 2); // 100console.log(10 ** 3); // 1000console.log(10 ** 4); // 10000
The **
operator is right-associative, meaning that the expression is evaluated from the right side of the **
to the left side.
console.log(10 ** 2 ** 2); // 10000
In the above code, 2 ** 2
is evaluated first. Then, 10 ** (result of 2 ** 2)
is evaluated.
So, a ** b ** c
will be evaluated as a ** (b ** c)
.
If we need to evaluate a ** b
and then ** c
, we can add parenthesis (as shown below):
// with parenthesisconsole.log((10 ** 2 ) ** 3); //10000// without parenthesisconsole.log(10 ** 2 ** 3); // 100000000
We will get a SyntaxError if we try to put a unary operator (+/-/~/!/delete/void/typeof) immediately before the base number (first number).
//console.log(-3 ** 3) // Syntax error// correct wayconsole.log((-3) ** 2) // 9console.log((-3) ** 3) // -27
We can combine **
with the assignment operator. Look at the code below:
// without Exponentiation assignmentlet a = 10;a = a ** 2;console.log(a);// with Exponentiation assignmentlet b = 10;b **=2; // 100console.log(b);
If any operand is not a number, then it is converted to a number using the Number()
constructor. The following code snippet demonstrates this:
console.log([] ** 10); // 0 because Number([]) -> 0 , 0 power anything is 0console.log(10 ** []); // 1console.log(10 ** [2]); // 100 , Number([2]) -> 2 , 10 power 2 is 100console.log("10" ** 2); // 100 , Number("10") -> 10 , 10 power 2 is 100console.log("10a" ** 2); // NaN , Number("10a") -> NaN , NaN power 2 is NaNconsole.log([10, 20] ** 2); // NaN , Number([10, 20]) -> NaN , NaN power 2 is NaN