None. As you can read in the ES7 spec, both Math.pow and the ** exponentation operator cast their arguments/operands to numbers and use the very same algorithm to determine the result.
Addendum: this changed with the introduction of the BigInt type in ES2020, whose values are only supported by operators (including **) but not the Math object.
Videos
None. As you can read in the ES7 spec, both Math.pow and the ** exponentation operator cast their arguments/operands to numbers and use the very same algorithm to determine the result.
Addendum: this changed with the introduction of the BigInt type in ES2020, whose values are only supported by operators (including **) but not the Math object.
Late to the party -- I just wanted to add that as much as there is no difference between the two ways, I recently came to realize that the ** exponentiation operator isn't supported in Internet Explorer, so developers that are interested in extensive cross-browser support for their applications, may prefer to choose the Math.pow(...) over the exponentiation operator.
Brief :
use parseInt or Math.floor to have y/2 as integer, unleness you will not reach 0 which is the stopper of recursion .
Details
if you want to transalte [C Algo]:
int power(int x, unsigned int y)
{
if( y == 0)
return 1;
else if (y%2 == 0)
return power(x, y/2)*power(x, y/2);
else
return x*power(x, y/2)*power(x, y/2);
}
To [JS Algo] , you will have :
function power(x,y){
if(y===0){return 1}
else if (y%2 ===0){
return power(x,parseInt(y/2))*power(x,parseInt(y/2))
}else{
return x*power(x,parseInt(y/2))*power(x,parseInt(y/2))
}
}
DEMO :
function power(x,y){
if(y===0){return 1}
else if (y%2 ===0){
return power(x,parseInt(y/2))*power(x,parseInt(y/2))
}else{
return x*power(x,parseInt(y/2))*power(x,parseInt(y/2))
}
}
console.log(power(3,2))
Try this out
It will give you the same result of JavaScript build in method ( Math.pi(x, y)) but the only problem is you can't use Power as decimal number.
Math.my_pow = (x, y) => {
if (typeof x != "number" || typeof y != "number")
throw "(x) and (y) should only be number";
if (y == 0) return 1;
if (x == 0 && y > 0 ) return 0;
const base = x;
var value = base;
var pow = y;
if (y < 0) pow = y * -1;
for (var i = 1; i < pow; i++) {
value *= base;
}
if (y < 0) return 1 / value;
return value;
};
try {
console.log( Math.my_pow(0, -3) );
console.log( Math.pow(0, -2) );
console.log( Math.my_pow(-5, -3) );
console.log( Math.pow(-5, -3) );
console.log( Math.my_pow(8, -7) );
console.log( Math.pow(8, -7)) ;
} catch (err) {
console.log(err);
}