
JavaScript Exponentiation Operator
The exponentiation operator (**
) in JavaScript is a mathematical operator that raises the left-hand operand to the power of the right-hand operand. It provides a concise way to perform exponentiation calculations.
Here’s an example of using the exponentiation operator:
var base = 2;
var exponent = 3;
var result = base ** exponent;
console.log(result); // Output: 8
In the example above, the **
operator is used to calculate base
raised to the power of exponent
. The result is stored in the result
variable, which is then logged to the console.
The exponentiation operator can be used with both integer and floating-point numbers. It also supports negative exponents and expressions with parentheses for more complex calculations.
console.log(3 ** 2); // Output: 9
console.log(4 ** 0.5); // Output: 2
console.log(2 ** -3); // Output: 0.125
console.log((1 + 2) ** 2); // Output: 9
In the above examples, we calculate the square of 3
, the square root of 4
, 2
raised to the power of -3
, and the square of the sum of 1
and 2
.
The exponentiation operator has right-to-left associativity, which means if there are multiple exponentiation operators in an expression, the calculation will be performed from right to left.
console.log(2 ** 3 ** 2); // Output: 512
In the example above, the calculation is evaluated as 2 ** (3 ** 2)
, resulting in 2
raised to the power of 9
, which is 512
.
The exponentiation operator is a convenient and concise way to perform exponentiation calculations in JavaScript, providing an alternative to using the Math.pow()
method or the Math.exp()
function.