Find the Power of a Number in Javascript
We will discuss two methods to solve this problem using Javascript

I am a Full stack developer.
Hi everyone today we Find the Power of a Number in Javascript. let's discuss how to solve this problem statement. if you want to check out yesterday's problem click here.
Given two integers as the number and power inputs, the objective is to raise the number input to the power input and print the value.
Method 1: Without While Loop
Method 2: With While Loop
Method 1: Without While Loop
Algorithm
step 1: Define the
mainfunction.step 2: Declare and initialize the
basevariable to 1.5.step 3: Declare and initialize the
expo1variable to 2.5.step 4: Declare and initialize the
expo2variable to -2.5.step 5: Declare the
res1andres2variables without initializing them.step 6: Use the
Math.powmethod to calculate the result ofbaseraised to the power ofexpo1and assign the result tores1.step 7: Use the
Math.powmethod to calculate the result ofbaseraised to the power ofexpo2and assign the result tores2.step 8: Use
console.logto output the value ofbaseraised to the power ofexpo1in the formatbase ^ expo1 = res1.step 9: Use
console.logto output the value ofbaseraised to the power ofexpo2in the formatbase ^ expo2 = res2.step 10: Call the
mainfunction to execute the code.
Javascript Code
function main() {
let base = 1.5;
let expo1 = 2.5;
let expo2 = -2.5;
let res1, res2;
// calculates the power
res1 = Math.pow(base, expo1);
res2 = Math.pow(base, expo2);
console.log(base + " ^ " + expo1 + " = " + res1);
console.log(base + " ^ " + expo2 + " = " + res2);
}
main();
Output
2 ^ 2 = 4
2 ^ -2 = 0.25
Method 2: With While Loop
Algorithm
step 1: Define the
mainfunction.step 2: Declare and initialize the
basevariable to 1.5.step 3: Declare and initialize the
expovariable to 2.step 4: Declare and initialize the
resvariable to 1.0.step 5: Enter a while loop that runs while
expois not equal to 0.step 6: Multiply the value of
resby the value ofbaseand assign the result tores.step 7: Decrement the value of
expoby 1.step 8: End the while loop.
step 9: Use
console.logto output the value ofresin the format"Result = " + res.step 10:Call the
mainfunction to execute the code.
Javascript Code
function main() {
let base = 2;
// Works only when exponent is positive integer
let expo = 2;
let res = 1.0;
while (expo !== 0) {
res *= base;
expo--;
}
console.log("Result = " + res);
}
main();
Output
Result = 4
Conclusion
So this article we solved the problem statement using javascript language. I hope you found this article helpful for your web development journey.
If you fill this article informative please like this article, if you have any suggestions please comment on this article, share it on social media and follow me on
Hashnode - Gaurav Patil
Twitter - @GauravYPatil




