Please support this book: buy it (PDF, EPUB, MOBI) or donate

4. Exponentiation operator (**)

The exponentiation operator (**) is an ECMAScript 2016 feature by Rick Waldron.

4.1 Overview

  1. > 6 ** 2
  2. 36

4.2 An infix operator for exponentiation

** is an infix operator for exponentiation:

  1. x ** y

produces the same result as

  1. Math.pow(x, y)

4.3 Examples

Normal use:

  1. const squared = 3 ** 2; // 9

Exponentiation assignment operator:

  1. let num = 3;
  2. num **= 2;
  3. console.log(num); // 9

Using exponentiation in a function (Pythagorean theorem):

  1. function dist(x, y) {
  2. return Math.sqrt(x**2 + y**2);
  3. }

4.4 Precedence

The exponentiation operator binds very strongly, more strongly than * (which, in turn, binds more strongly than +):

  1. > 2**2 * 2
  2. 8
  3. > 2 ** (2*2)
  4. 16

4.5 Further reading