I have read articles on the internet to better understand recursive functions, but I did not find an answer to what eludes me.
In the Replace Loops using Recursion from the JavaScript section we have the following code:
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}
What I would like to understand is when the function is invoked what is the value of multiply(arr, n -1)?
Let’s say the function is invoked like this
multiply([2, 3, 6, 5, 8], 5);
So in the first iteration, the return line would be:
return multiply([2, 3, 6, 5, 8], 4) * arr[4];
I don’t understand how we are multiplying [2, 3, 6, 5, 8], 4 to arr[4] (8 in our case).
I found this example:
function factorial(x) {
// TERMINATION
if (x < 0) return;
// BASE
if (x === 0) return 1;
// RECURSION
return x * factorial(x - 1);
}
factorial(3);
// 6
of a recursion that makes sense to me because we are multiplying by a single number when the recursion occurs, but I don’t understand how the example from freeCodeCamp works.
Thank you in advance