What is the exponentiation ** operator in JavaScript?

The exponentiation operator (**) will return the first operand’s power of the second operand.

a ** b is equivalent to aba^{b}, which is equivalent to Math.pow(a, b)

console.log(10 ** 2); // 100
console.log(10 ** 3); // 1000
console.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 parenthesis
console.log((10 ** 2 ) ** 3); //10000
// without parenthesis
console.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 way
console.log((-3) ** 2) // 9
console.log((-3) ** 3) // -27

We can combine ** with the assignment operator. Look at the code below:

// without Exponentiation assignment
let a = 10;
a = a ** 2;
console.log(a);
// with Exponentiation assignment
let b = 10;
b **=2; // 100
console.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 0
console.log(10 ** []); // 1
console.log(10 ** [2]); // 100 , Number([2]) -> 2 , 10 power 2 is 100
console.log("10" ** 2); // 100 , Number("10") -> 10 , 10 power 2 is 100
console.log("10a" ** 2); // NaN , Number("10a") -> NaN , NaN power 2 is NaN
console.log([10, 20] ** 2); // NaN , Number([10, 20]) -> NaN , NaN power 2 is NaN

Free Resources