JavaScript Program to Compute Iterative Power of a Number
Last Updated :
13 Sep, 2023
This article will demonstrate how to compute the iterative power of a number using JavaScript. It will include iterative methods to calculate and display the power of a given number.
Methods to Compute the Iterative Power of a Number
- Using JavaScript for loop
- Using JavaScript while loop
- Using recursion
- Using the JavaScript array method
Method 1: Using JavaScript for Loop
In this method, we will use JavaScript for loop to iterate and calculate output by multiplication.
Example: In this example, we will calculate the output of 5 to power 3.
Javascript
let n = 5
let power = 3
let num = 1;
for (let i = 0; i < power; ++i){
num = num * n;
}
console.log(num);
|
Method 2: Using JavaScript while Loop
In this method, we will use JavaScript while loop to iterate and calculate output by multiplication.
Example: In this example, we will calculate the output of 7 to power 3.
Javascript
let n = 7
let power = 3
let num = 1;
while (power) {
num = num * n;
power -= 1;
}
console.log(num);
|
Method 3: Using Recursion
In this method, we will use a recursive function to iterate and perform multiplication at every iteration.
Example: In this example, we will calculate 8 to the power 3 using recursion.
Javascript
function pow(n, p) {
if (p == 1) return n;
return n * pow(n, p - 1);
}
let n = 8
let power = 3
console.log(pow(n, power));
|
Method 4: Using the JavaScript array methods
In this approach, we will use JavaScript array methods like array constructor, fill and reduce methods to calculate the power of the given number
Syntax:
// Creating array
arr = new Array(total elements).fill(value)
arr.reduce((accumulator , value)=> accumulator*value, initial value of accumulator)
Example: In this example, we will print the value of 2 to power 5
Javascript
let n = 2;
let power = 5;
let numArray = new Array(power).fill(n);
let result = numArray.reduce((res, n) => (res *= n), 1);
console.log(result);
|
Share your thoughts in the comments
Please Login to comment...