Skip to content

JavaScript power operator | Example code

  • by

JavaScript has an exponentiation operator (**), that can call a power operator. This operator raises the first operand to the power of the second operand.

x ** y

Another way you can use is the Math pow() method.

JavaScript power operator

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script >
    let number = 2;
    let exponent = 3;

    //using the exponent operator
    console.log( number ** exponent);

    // using the Math library 
    console.log(Math.pow(number, exponent));
  </script>
</body>
</html>

Output:

JavaScript power operator

The exponentiation assignment operator (**=) raises the value of a variable to the power of the right operand.

let x = 5;
console.log(x **= 2) //25

More examples

console.log(3 ** 4); // 81

console.log(10 ** -2); // 0.01

console.log(2 ** 3 ** 2); // 512

console.log((2 ** 3) ** 2); // 64

Usage with unary operators

To invert the sign of the result of an exponentiation expression:

-(2 ** 2) // -4

To force the base of an exponentiation expression to be a negative number:

(-2) ** 2 // 4

Do comment if you have any doubts or suggestions on this Js operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading