In this article, we will learn how to find the power of a number in JavaScript.
Here is a small example of getting the exponent power of a number.
62 = 6 * 6 , the value is 36.
Here, 6 is the base number and 2 is the exponent.
JavaScript provides us with a handy function, Math.pow()
to perform the above calculation easily.
However, in this article, we will perform the calculation in two different ways using:
Let's check each method with an example.
The Math.pow()
in JavaScript returns the base to the exponent power i.e xy value.
It takes two arguments: base and exponent.
Syntax:
Math.pow(base, exponent)
argument | description |
---|---|
base | The base number. |
exponent | the value used to raise the base number. |
Let's use the function to raise the base number in JavaScript.
const b = 5;
const e = 2;
console.log(Math.pow(5,2)) // 25
This is the easy way to raise a number to a power in Javascript.
However, if you don't want to use the Math.pow()
function, you can code the function manually using for
loop.
First, let's understand how we will code the loop JavaScript function.
Let's see an example of calculating power of a number.
62 = 6 * 6 , the value is 36 (6 is the base and 2 is the exponent)
So, to perform this using for
loop, we have to loop exponent times and multiple the base number on each loop.
Example:
function powOfNum(b,e){
pow = 1;
for(var i=0; i<e; i++){
pow = pow*b;
}
return pow;
}
console.log(powOfNum(5,2)) // 25
In the above code, we have created a function powOfNum()
, which will take two arguments (b, e) i.e base and exponent.
It then loops the exponent number of times and the multiplied base value is stored in pow , which is returned once the condition (i<e
) turns false .