Understanding how this works?

Tell us what’s happening:
I was able to put the right code together, but I still don’t really understand how the recursive case is working.

I guess my question is: why are we using a subtraction operator in the function that’s supposed to be adding them? ie, the n - 1 parts within the function. How is it getting 9 from sum([2, 3, 4, 5], 3) ?

I know the explanation is probably pretty simple, I just can’t wrap my head around it right now haha.

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 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36.

Challenge: Replace Loops using Recursion

Link to the challenge:

the subtraction is for the index inside the function call, but if you look at the return statement, it is a sum

1 Like

So the sum is cancelling out the subtractions / they aren’t actually subtracting?
If you could maybe pseudo-code that bit for me that might help a bit more. Thank you for the reply!

you have two different things going on:
the return statement is
return sum(arr, n-1) + arr[n-1]

in case of sum([2,3,4,5], 3) it is return sum([2,3,4,5], 2) + arr[2]
so it has chanced the n to be one lower in the function call, and it is summing that function call to a member in the array

and it is taking the third element in the array (arr[2]) and calling the function to sum the first two elements

1 Like

Ah, now I get it! :sweat_smile:
Dang, thank you so much!!