Looking to create a recursive function that calculates the powers of a number and adds each result to an array named "stack".
This means that with each recursion, a new value will be appended to the stack.
For instance, if we use power(3, 3)
, our stack should then contain: [3, 9, 27]
.
The issue I'm encountering is getting only the last power value (27) instead of the full array. What could be wrong in my code?
// Initialize an empty array called "stack"
var stack = [];
// Recursive function implementation
function power(base, exponent) {
// Base case
if (exponent === 0) {
return 1;
}
// Recursion case
else {
stack[exponent - 1] = base * power(base, exponent - 1);
return stack[exponent - 1];
}
}
power(3, 3);