Exponentiation (**) in JavaScript

In mathematics, exponentiation is a way to multiply a number by itself a certain number of times (or phrased differently, to the power of the second operand).

In JavaScript, the exponentiation operator is represented by two asterisks (**).

It's also a more concise and readable alternative to the older Math.pow() method.

How to Use It?

Here's the basic format:

base ** exponent
  • base is the number you want to multiply.
  • exponent is the number of times you want to multiply the base by itself.

Example:

2 ** 3 // This equals 8 because 2 multiplied by itself 3 times is 2 * 2 * 2 = 8.

More examples 🧠

  • 3 ** 2 will give you 9 because 3 multiplied by itself is 9.
  • 5 ** 3 will give you 125 because 5 multiplied by itself 3 times is 125.
  • 10 ** 0 will give you 1 because any number raised to the power of 0 is always 1.

Math.pow()

In case you haven't used it in JavaScript, before exponential operators, we used the Math.pow() method to calculate powers.

For example:

Math.pow(2, 3) // This also equals 8.

But I think with the ** operator, the code becomes shorter and more readable.

Tips:

  • If you use a negative exponent, the result will be a fraction. For example, 2 ** -3 is 1/8.
  • Always remember the order: the base comes before the **, and the exponent comes after.
  • Unlike Math.pow(), the exponential operator allows you to use BigInt values.

Happy coding! 🪄

JavaScriptJS
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.