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 you9
because 3 multiplied by itself is 9.5 ** 3
will give you125
because 5 multiplied by itself 3 times is 125.10 ** 0
will give you1
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
is1/8
. - Always remember the order: the base comes before the
**
, and the exponent comes after. - Unlike
Math.pow()
, the exponential operator allows you to useBigInt
values.
Happy coding! 🪄