Summary: in this tutorial, you will learn how to use the JavaScript exponentiation operator (**) to raise a number to the power of an exponent.
Introduction to the JavaScript exponentiation operator #
To raise a number to the power of an exponent, you often use the static method Math.pow() with the following syntax:
Math.pow(base, exponent)For example:
let result = Math.pow(2,2);
console.log(result); // 4
result = Math.pow(2,3);
console.log(result); // 8ECMAScript 2016 provided an alternative way to get a base to the exponent power by using the exponentiation operator ( **) with the following syntax:
x**nThe operator ** raises the x to the power of an exponent n.
Note that some languages use the caret symbol ^ for exponentiation. However, JavaScript already uses that symbol for the bitwise logical XOR operator.
The following example illustrates how to use the exponentiation operator (**):
let result = 2 ** 2;
console.log(result); // 4
result = 2 ** 3;
console.log(result); // 8The Math.pow() accepts a value and converts it to a value of the number type for calculation. Similarly, the operator ** accepts values of the number type. In addition, the operator ** accepts a value of the bigint type. For example:
let result = 2n ** 3n;
console.log(result); // 8nYou can also use the exponentiation operator ( **) in the infix notation. For example:
let x = 2;
x **= 4;
console.log(x); // 16JavaScript does not allow you to put a unary operator immediately before the base number. If you attempt to do so, you’ll get a SyntaxError.
The following example causes a syntax error:
let result = -2**3;Error:
Uncaught SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedenceTo fix this, you use parentheses like this:
let result = (-2)**3;
console.log(result); // -8Summary #
- The exponentiation operator
**raises a number to the power of an exponent. - The exponentiation operator
**accepts values of the typenumberorbigint.
Thank you for your feedback!