Tell us what’s happening:
Describe your issue in detail here.
I was able to complete this challenge only by looking at the example given and substituting the multiply(*) operator with the sum(+) operator and changing the function name from multiply to sum. I can’t after much thought and several videos figure out what is exactly happening. Let’s use this example —
sum ([2, 3, 4, 5] , 3 ) — I know that what the problem asks is for the sum of the first ‘n’ elements in the array, which is in this case 3 so that means 2 + 3 + 4 = 9. I don’t understand how sum (arr, n-1) + arr [ n - 1 ]; gets me there. If I replace n with 3 in this case doesn’t that then leave me with sum (arr, 2) + arr[ 2 ] ? If I use 0 indexing doesn’t that equate to 4 + 4? I need to understand what is happening in sum( arr, n-1) + arr[ n - 1 ] when I switch in a “arr” and “n” as in the function sum(arr, n) ie. what does — ‘sum(arr, n-1)’ — represent and what does— 'arr[ n-1]-- represent. If someone could please help me understand this with a detailed explanation I would be very grateful. Thanks in advance. Your code so far

function sum(arr, n) {
// Only change code below this line
if (n <= 0) {
return 0;
} else {
return sum(arr, n-1) + arr[n - 1];
}
// Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Replace Loops using Recursion

Let’s review. You correctly said above that if n = 3 and so we call the function as sum(arr, 3) then it will return sum(arr, 2) + arr[ 2 ] and replacing arr[2] with its value gives you sum(arr, 2) + 4.

Then I asked you what sum(arr, 2) returns. I need you to do the same thing you did above for sum(arr, 3) except this time for sum(arr, 2).

I am assuming (arr, 1) , but if I take away 1 from (arr, 2) don’t I have to take away another 1 from arr[2] changing the number? is the “2” in (arr, 2) literally just the 2 elements “2” + “3”, so no 0 index.

Not quite, sum([2, 3, 4, 5], 2) cannot return sum([2, 3, 4, 5], 2) + 4 because then we’d be stuck making the same call back to sum([2, 3, 4, 5], 2) forever and ever and ever and ever.