Exponentiation ** (power) operator in Javascript
Published in
2 min readJul 25, 2019
The ** operator returns the result of the first variable to the power of the second variable. That is, Math.pow(a,b)
.
var a = 2;
var b = 5;a ** b; // 32Math.pow(a, b); // 32
If we do like a ** b ** c
, then the operation is computed from right-to-left , that is a ** (b**c)
var a = 5, b = 2, c = 2;a ** b ** c; // 625// Execution order of a ** b ** c;(5 ** (2 ** 2) )(5 ** 4)625
You cannot put a unary operator (+/-/~/!/delete/void/typeof
) immediately before the base number.
// Invalid Operations+a ** b;-a ** b;~a ** b;!a ** b;delete a ** b;void a ** b;typeof a ** b;// All the above operation are invalid and result in Uncaught SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence
Handling negative numbers
-2 ** 2; //invalid// The above expression can be converted into (-2) ** 2; // 4(-2) ** 3; //-8
Any operation on NaN
is NaN
NaN ** 1; //NaNNaN ** NaN; // NaN
What will happen on using undefined:
1 ** undefined; // NaN// because1 ** Number(undefined);1 ** NaN; // NaN
Similarly when we do **
on null
, Number(null) → 0
, so the power of 0 is 1.
10 ** null; // 1// because10 ** Number(null); // Number(null) --> 010 ** 0; // 1
If you find this helpful surprise 🎁 me here.
Share if you feel happy 😃 😆 🙂 .
Follow Javascript Jeep🚙💨