Hi all,
I’m working on replacing loops using recursion but am realizing that I’m not understanding something with functions. I am simply trying to console.log this example before I try to make it a recursive function:
function multiply(arr, n) {
let product = 1;
for (let i = 0; i < n; i++) {
product *= arr[i];
}
return product;
}
However, notice that multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]
. That means you can rewrite multiply
in terms of itself and never need to use a loop. (End of example)
How would I console.log the above example to better understand what is happening with that function. Also, I’m not sure I understand why the “n” is “n - 1”. Any advice would be appreciated. Thanks
function sum(arr, n) {
// Only change code below this line
if (n <= 0) {
return 1;
} else {
return add(arr, n-1) + arr[n-1];
}
// Only change code above this line
}
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
Challenge: Basic JavaScript - Replace Loops using Recursion
Link to the challenge: