Tell us what’s happening:
I’m trying to make sense of the function in the example, that multiplies the elements from 0
to n
inclusive in an array to create the product of those elements.
In my understanding, it starts from the n-th array element, which in my case is 6, multiplies it by the (n-1)-th element, which is now 5 and iterates until n = 0.
Is there a way to log the return of every iteration? I would like to see something like this:
30
120
360
720
Your code so far
function multiply(arr, n) {
if (n <= 0) {
return arr[0];
} else {
return multiply(arr, n - 1) * arr[n];
}
}
console.log(multiply([2, 3, 4, 5, 6, 7, 8, 9], 4));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36
.
Challenge: Replace Loops using Recursion
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion