Exponentiation operator in JavaScript

exponentiation operator is one of the minor features introduced in EcmaScript2017(ES7) language.

It uses two asterisk symbols ** on two operands to return the result with the first operand multiplied by the power of the second operand. Important points

  • This is a replacement of the Math.pow(m,n) function in the Math library
  • used in arithmetic, scientific, and 3D calculations
  • Both operands are variables or constants
  • right-associative i.e. right to left, applied when multiple exponential operators are used.
  • Shorter syntax for the power of values.

Syntax of exponentiation operator:

Operand1 ** Operand2 // is equal to Operand1 power of Operand2

Operand1 is called a Base. Operand2 is called an exponent. For example, 5***3 is equal to 5 power of 3 is equal to 5*5*5 (125)

var m = 3;
var n = 2;
m ** n; // 9
Math.pow(m,n) // 9 returned

Grouping operators from right to left:

the operator is right-associative which means applies from right to left

m ** n ** 0 is equal to m ** (n ** o)

3 ** 2 ** 2 equal to 3**(2**2) // returns 91

Let’s see some valid and invalid examples.

Binary operator, Unary operator is not allowed

Unary operators like +,-, delete, and void are not allowed for the base.

Invalid usage

+2 **4
-2** 5

The above code results compilation error.

unknown: Illegal expression. Wrap the left-hand side or entire exponentiation in parentheses.

Exponent operator on NAN, null,undefined values

  • Applying any operator on NAN as an exponent result always in NAN.
  • Null will be treated as zero and apply null results to 1
  • undefined exponent results in NAN
2 ** NAN //NAN
2 ** undefined //NAN
2 ** null // 1

Exponentiation Operator Assignment(**=) example

Assignments are shorthand operators for Exponentiation operations.

For example

p**=q is equal to p=p** q

Here is an example

var m = 3;
console.log(m **=3); // 27
console.log(m **='abc'); // NAN

Like a normal operator, if used with a string, it returns the NAN value.