ES6(+!) Every Day: ES2016’s Exponentiation Operator
A little about the series and the author
What is it and what can it do?
The Exponentiation Operator is one of ECMAscript 2016’s newest features. In order to be compatible with all browsers, etc, the Babel transpiler transforms this binary arithmetic operator into a Math.pow() method when passed through it. In this case as well as in the pre-ES2016 method, the left operand becomes the base and the right becomes the exponent. The double asterisk is said to have a “tighter bind” than the single asterisk.
Math.pow(3, 4); // pre-ES2016 - returns 81
3 ** 4 // ES2016 - returns 81
Commutativity and Associativity
The Exponentiation Operator is NOT commutative in that the result is dependent on the order of operands.
1 ** 6 // returns 1 - not the same as...
6 ** 1 // returns 6
However, it IS associative in that exponents take precedence based on their order within parenthesis. In this case, the exponentiation Operator is right-associative because expressions where it occurs multiple times is always parenthesized from the right.
6 ** 2 ** 2 // returns 1296 - is the same as...
6 ** (2 ** 2) or 6 ** 4 // returns 1296
Negatives and Non-Integers
The same rules apply for using negatives and non-integers with the Exponentiation Operator as for Math.pow(), EXCEPT negative bases are ALWAYS parenthesized. This rule does not apply to negative exponents. The rule exists this way to avoid possible ambiguous intent as well as added confusion.
Non-integers are treated much the same way using the Exponentiation Operator. Exponentiation takes precedence in order of operations.
4 ** -4 // returns 0.00390625 is the same as...
1/4 ** 4 // returns 0.00390625
Assign and combine
let c = 10;
c **= 2; // returns 100
Want more info? Check out these Resources:
ECMAScript 2016 will likely standardize the exponentiation operator **. Babel and TypeScript 1.7 already support it…blog.mariusschulz.com
The exponentiation operator (`**`) is an ECMAScript proposal by Rick Waldron. It is at stage 4 (finished) and part of…2ality.com