JavaScript Exponentiation Operator

Created with Sketch.

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); // 8

Code 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); // 8

Code language: JavaScript (javascript)

Both Math.pow() and operator ** accept values of the number type. However, the operator ** also accepts the numbers of the bigint type. For example:

let result = 2n ** 3n;
console.log(result); // 8n

Code language: JavaScript (javascript)

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

let x = 2;
x **= 4;
console.log(x); // 16

Code language: JavaScript (javascript)

JavaScript doe 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 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 precedence

Code language: JavaScript (javascript)

To fix this, you use parentheses like this:

let result = (-2)**3;
console.log(result); // -8

Code 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.

Leave a Reply

Your email address will not be published. Required fields are marked *