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
baseis the number you want to multiply.exponentis 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 ** 2will give you9because 3 multiplied by itself is 9.5 ** 3will give you125because 5 multiplied by itself 3 times is 125.10 ** 0will give you1because 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 ** -3is1/8. - Always remember the order: the base comes before the
**, and the exponent comes after. - Unlike
Math.pow(), the exponential operator allows you to useBigIntvalues.
Happy coding! 🪄
