Open In App

JavaScript Program to Calculate Power Using Recursion

Last Updated : 20 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A program to calculate power using recursion involves defining a function that recursively multiplies a base number by itself, decrementing the exponent until it reaches 0. The below-listed examples can be utilized to calculate powers using recursion in JavaScript.

Using Recursion

Basic recursion involves defining a function that calls itself with modified parameters until reaching a base case, where a specific condition is met. This approach simplifies solving complex problems by breaking them down into smaller, self-repeating tasks.

Example: The below code recursively calculates the power of the passed base number in JavaScript.

Javascript




function myPowerFunction(base, exponent) {
    if (exponent === 0) {
        return 1;
    }
    const result =
        base * myPowerFunction(base, exponent - 1);
    return result;
}
const b = 2;
const e = 4;
console.log
    (`The recursively calculated value of ${b}^${e} is: ${myPowerFunction(b, e)}`);


Output

The recursively calculated value of 2^4 is: 16

Using Memoization with Recursion

Memoization optimizes recursive functions by caching computed results. Before computing, the function checks if the result for given inputs exists in the cache it returns the cached result. Otherwise, it computes the power, stores, and returns it. This reduces redundant computations, enhancing performance.

Example: The below code will use memoization technique with recursion to improve the performance.

Javascript




const memo = {};
 
function myPowerFunction(base, exponent) {
    const key = base + ',' + exponent;
    if (key in memo) {
        return memo[key];
    }
    if (exponent === 0) {
        return 1;
    }
    const result =
        base * myPowerFunction(base, exponent - 1);
    memo[key] = result;
    return result;
}
 
const b = 3;
const e = 4;
console.log
    (`The recursively calculated value of ${b}^${e} is: ${myPowerFunction(b, e)}`);


Output

The recursively calculated value of 3^4 is: 81


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads