Exponentiation Operator (**) in JavaScript

🔍 What is the Exponentiation Operator?

The exponentiation operator ** is used to raise a number to the power of an exponent. It was introduced in ES2016 (ES7) and offers a clean, concise syntax for exponentiation.

📚 Syntax

Code Snippet

base ** exponent

Here, base is the number you want to raise, and exponent is the power you want to raise it to.

🧪 Examples

Basic Usage

console.log(2 ** 3);    // 8 (2 * 2 * 2)
console.log(5 ** 0);    // 1 (anything to the power of 0)
console.log(4 ** 0.5);  // 2 (square root of 4)

⚙️ Comparison with Math.pow()

The exponentiation operator provides a shorter and more readable alternative to Math.pow(base, exponent).

Code Snippet

console.log(Math.pow(2, 3));  // 8
console.log(2 ** 3);          // 8

📌 Operator Precedence

The exponentiation operator has higher precedence than multiplication and division, but it is right-associative.

Code Snippet

console.log(2 ** 3 ** 2); // 512, because it is evaluated as 2 ** (3 ** 2)

⚠️ Important Notes

  • Negative exponents return fractional numbers:

Code Snippet

console.log(2 ** -2); // 0.25 (which is 1 / (2 ** 2))
  • Use parentheses to control order of evaluation when mixing with other operators.

🧾 Summary

  • ** raises a base to a power (exponent).
  • It is a more concise and readable alternative to Math.pow().
  • Operator is right-associative and has high precedence.
  • Supports fractional and negative exponents.
>>“Exponentiation operator makes power calculations elegant and simple!”

🔗 References