JavaScript Program to Find Power Using Recursion
function power(base, exponent) { if (exponent === 0) return 1; return base * power(base, exponent - 1); } which multiplies the base by itself exponent times recursively.Examples
How to Think About It
Algorithm
Code
function power(base, exponent) { if (exponent === 0) { return 1; } return base * power(base, exponent - 1); } console.log(power(2, 3)); // Output: 8 console.log(power(5, 0)); // Output: 1 console.log(power(3, 1)); // Output: 3
Dry Run
Let's trace power(2, 3) through the code
Initial call
power(2, 3) checks if exponent === 0 (false), returns 2 * power(2, 2)
Second call
power(2, 2) checks if exponent === 0 (false), returns 2 * power(2, 1)
Third call
power(2, 1) checks if exponent === 0 (false), returns 2 * power(2, 0)
Base case
power(2, 0) returns 1 because exponent === 0
Return values
power(2, 1) returns 2 * 1 = 2 power(2, 2) returns 2 * 2 = 4 power(2, 3) returns 2 * 4 = 8
| Call | Exponent | Return Value |
|---|---|---|
| power(2, 0) | 0 | 1 |
| power(2, 1) | 1 | 2 |
| power(2, 2) | 2 | 4 |
| power(2, 3) | 3 | 8 |
Why This Works
Step 1: Base Case
The function stops calling itself when the exponent is zero by returning 1, because any number to the power of zero is 1.
Step 2: Recursive Step
For exponents greater than zero, the function multiplies the base by the result of the same function with the exponent decreased by one.
Step 3: Building the Result
Each recursive call waits for the smaller problem to solve, then multiplies the base, building up the final power value.
Alternative Approaches
function powerLoop(base, exponent) { let result = 1; for (let i = 0; i < exponent; i++) { result *= base; } return result; } console.log(powerLoop(2, 3)); // 8
function powerOperator(base, exponent) { return base ** exponent; } console.log(powerOperator(2, 3)); // 8
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself once per decrement of the exponent, so it runs in linear time relative to the exponent.
Space Complexity
Each recursive call adds a new layer to the call stack, so space used is proportional to the exponent.
Which Approach is Fastest?
Using the built-in exponentiation operator is fastest and uses constant space, while recursion is easier to understand but uses more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursion | O(n) | O(n) | Learning recursion and simple cases |
| Loop | O(n) | O(1) | Avoiding call stack overhead |
| Exponentiation Operator | O(1) | O(1) | Fastest and simplest in JavaScript |