The exponentiation operator

The exponentiation operator (**) takes two operands, a base on the left side and an exponent on the right side. It will evaluate to the base raised to the power of the exponent:

10 ** 2; // => 100
10 ** 3; // => 1,000
10 ** 4; // => 10,000

It is functionally identical to using the Math.pow(a, b) operation, although is more succinct. As with other arithmetic operations, it will internally coerce its operands to the Number type, and passing in any operands of NaN, Infinity, or zero will result in possibly unexpected outcomes, so you should try to avoid such cases.

One curious case worth mentioning is that, if the exponent is zero, then the result will always be 1, regardless of what the base is. So, the base could even be InfinityNaN, or anything else, and the result would still be 1:

1000 ** 0;     // => 1
0 ** 0; // => 1
Infinity ** 0; // => 1
NaN ** 0; // => 1

All other arithmetic operators will evaluate to NaN if one of their operands is NaN, so the behavior of ** here is quite unique. Another unique behavior is that it will throw SyntaxError if your first operand is itself a unary operation:

+2 ** 2;
// SyntaxError: Unary operator used immediately
// before exponentiation expression. Parenthesis
// must be used to disambiguate operator precedence

This is to prevent ambiguity for the programmer. Depending on their previous exposure to other languages (or strict mathematical notation), they may expect cases such as -2 ** 2 to be either 4 or -4. As such, JavaScript will throw in such cases, hence forcing you to be more explicit with either (-2) ** 2 or -(2 ** 2).

Apart from these unique characteristics, the exponentiation operator can be considered similar to other binary (two-operand) arithmetic operators. As always: be aware of your operands' types and how they may be coerced!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.46.36