The exponentiation (**) operator is used to return the result of raising the first operand(the base) to the power of the second operand(the exponent).
The ** operator is right-associative, meaning that in an expression, it is evaluated from right to left.
Syntax
x ** y
Visual Representation
Example 1: Use of Exponentiation operator
console.log(2 ** 4); // 2 raised to the power of 4
console.log(2 ** -4); // 2 raised to the power of -4
Output
16
0.0625
We can achieve the same output using the Math.pow() function.
console.log(Math.pow(2, 4)); // 2 raised to the power of 4
console.log(Math.pow(2, -4)); // 2 raised to the power of -4
Output
16
0.0625
Example 2: Usage with unary operators
To invert the sign of the result of an exponentiation expression:
console.log(-(2 ** 2));
Output
-4
To force the base of an exponentiation expression to be a negative number:
console.log((-2) ** 2);
Output
4
Example 3: Exponentiation Assignment
The exponentiation assignment operator (**=) is used to raises a variable’s value to the power indicated by the operand on its right.
let a = 5;
a **= 4;
console.log(a);
Output
625
Example 4: Operand is not a number
If any operand is not a number, it is converted to a number using the Number() constructor.
console.log([] ** 11);
console.log(21 ** []);
console.log(21 ** [2]);
console.log("21" ** 2);
console.log("21k" ** 2);
console.log([19, 21] ** 2);
Output
0
1
441
441
NaN
NaN
Example 5: Associativity
console.log(1 ** 2 ** 3);
console.log(2 ** (3 ** 4));
console.log((2 ** 3) ** 4);
Output
1
2.4178516392292583e+24
4096
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.