JavaScript Exponentiation Operator

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)Code language: JavaScript (javascript)

For example:

let result = Math.pow(2,2);
console.log(result); // 4

result = Math.pow(2,3);
console.log(result); // 8Code language: JavaScript (javascript)

ECMAScript 2016 provided an alternative way to get a base to the exponent power by using the exponentiation operator ( **) with the following syntax:

x**n

The 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); // 8Code language: JavaScript (javascript)

The 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); // 8nCode language: JavaScript (javascript)

Also, you can use the exponentiation operator  ( **) in the infix notation. For example:

let x = 2;
x **= 4;
console.log(x); // 16Code language: JavaScript (javascript)

JavaScript 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;Code language: JavaScript (javascript)

Error:

Uncaught SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedenceCode language: JavaScript (javascript)

To fix this, you use parentheses like this:

let result = (-2)**3;
console.log(result); // -8Code language: JavaScript (javascript)

Summary

  • The exponentiation operator ** raises a number to the power of an exponent.
  • The exponentiation operator ** accepts values of the type number or bigint.
Was this tutorial helpful ?