Open In App

JavaScript Program to Compute Iterative Power of a Number

Last Updated : 13 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Base number input
let n = 5
  
// Power input
let power = 3
  
// Result variable
let num = 1;
for(let i = 0; i < power; ++i){
      num = num * n; 
}
  
// Display output
console.log(num);


Output

125

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




// Base number input
let n = 7
  
// Power input
let power = 3
  
// Result variable
let num = 1;
while (power) {
    num = num * n;
    power -= 1;
}
  
// Display output
console.log(num);


Output

343

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




// Recursive function to compute Power
function pow(n, p) {
    if (p == 1) return n;
    return n * pow(n, p - 1);
}
  
// Base number input
let n = 8
  
// Power input
let power = 3
  
// Display output
console.log(pow(n, power));


Output

512

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




// Base number input
let n = 2;
  
// Power input
let power = 5;
  
// Creating new array having value n
let numArray = new Array(power).fill(n);
  
// Calculate the result output
let result = numArray.reduce((res, n) => (res *= n), 1);
  
// Display output
console.log(result);


Output

32


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads