Exponentiation ** operator in Javascript

The ** operator returns the result of the first variable to the power of the second variable. That is, Math.pow(a,b).

Photo by Crissy Jarvis onย Unsplash
var a = 2;
var b = 5;
a ** b; // 32
Math.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; //NaN
NaN ** NaN;  // NaN

What will happen on using undefined:

1  ** undefined; // NaN
// because
1 ** Number(undefined);
1 ** NaN; // NaN

Similarly when we do ** on null, Number(null) โ†’ 0, so the power of 0 is 1.

10 ** null; // 1
// because
10 ** Number(null); // Number(null) --> 0
10 ** 0; // 1

If you find this helpful surprise ๐ŸŽ me here.

Share if you feel happy ๐Ÿ˜ƒ ๐Ÿ˜† ๐Ÿ™‚ย .

Follow Javascript Jeep๐Ÿš™๐Ÿ’จ


https://gitconnected.com/learn/javascript

Leave a comment

Design a site like this with WordPress.com
Get started