In JavaScript, the Exponentiation Assignment Operator (**=) is used to raise a variable to the power of the right-hand operand and assign the result back to the variable. It provides a shorter and more readable way to perform exponentiation. This operator works the same way as the Math.pow() method.
- Raises the left-hand variable to the power of the right-hand operand.
- Stores the computed result back into the same variable.
- Functionally equivalent to using Math.pow() for exponentiation.
let num = 3;
// Exponentiation assignment
num **= 4; // num = num ** 4
console.log(num);
Syntax:
a **= b
or
a = a ** b
[Example 1]: We will use the exponentiation assignment operator.
let x = 6;
console.log(x **= 2);
console.log(x **= 0);
console.log(x **= 'bar');
- x **= 2 → Raises x (6) to the power of 2, so x becomes 36.
- x **= 0 → Any number raised to the power 0 is 1, so x becomes 1.
- x **= 'bar' → The string 'bar' cannot be converted to a number, so the result is NaN.
[Example 2]: We will use the exponentiation operator to the NaN.
let x = NaN;
console.log(x **= 2);
- x is assigned the value NaN.
- x **= 2 attempts to raise NaN to the power of 2.
- Any arithmetic operation involving NaN results in NaN, so the output is NaN.