Just hoping this isn't a duplicate inquiry, as I've searched extensively but couldn't find the solution.
I'm currently experimenting with recursive functions (I'm relatively new to this), attempting to multiply each number in an array akin to calculating a factorial. However, despite having written the code below, it only returns undefined
as the output.
Here is the code snippet:
var stack = [];
function countDown(int) {
stack.push(int);
if (int === 1) {
return 1;
}
return countDown(int - 1);
}
function multiplyEach() {
// Remove the last value of the stack
// and assign it to the variable int
int = stack.pop();
x = stack.length;
// Base case
if (x === 0 ) {
return;
}
// Recursive case
else {
stack[int - 1] = int * stack[x - 1];
return multiplyEach(int);
}
}
// Call the function countDown(7)
countDown(7);
// Print out the returned value by multiplyEach()
console.log(multiplyEach());
Your insights will be greatly appreciated. Thank you!
Cheers!