ES2016 introduced the exponentiation operator
[00:02] ECMAScript 2016 introduced a new binary arithmetic operator for exponentiation. It's written as some number ** some umber. It returns the result of raising the left-hand side to the power of the right-hand side. That is, the left operand represents the base, and the right operand represents the exponent.
[00:41] Note that exponents don't have to be integers. For example, you can raise a value to a power of one-half to compute a square root. You can also use negative exponents, and just like in mathematics 10^-2 is equivalent to 1/10^2.
[00:59] While you don't have to parenthesize negative exponents, you do have to parenthesize negative bases. Therefore -10**2 is not a valid expression on its own. You have to parenthesize either the base -10, or the expression 10^2, depending on which of the two you actually mean.
[01:36] Just like in mathematics, exponentiation has a higher precedence than multiplication or division. This means you can write 5x10^2 and get the expected value of 500. Another way to put it is that ** binds tighter than *.
[01:52] Associativity on the other hand, determines how operators of the same precedence are grouped in the absence of parentheses. The exponentiation operator is right associative, which means it's grouped from the right. Therefore 2^3^2 is implicitly grouped like this.
[02:13] Notice that grouping from the left results in a different value. I recommend you always parenthesize expressions in which the exponentiation operator occurs multiple times, otherwise it's just too easy to misinterpret the meaning of the expression.
[02:55] Finally, let's take a look at how Babel transpiles the exponentiation operator. I've added a .babelrc configuration file, and I've also installed the ES2015 and ES2016 presets. I've also created an index.js file, which uses the exponentiation operator in a square function.
[03:13] If I now run Babel, you'll see that in the generated code the exponentiation expression has been replaced by a call to the math.pow function. For any given base and exponent, the exponentiation operator and math.pow will compute the same value.