Help wanted to better understand recursion!

While I was able to pass this lesson to be perfectly honest i’m having some trouble understanding how exactly in this recursive function, when called, did sum([2, 3, 4], 1) equal 2.

function sum(arr, n) {

// Only change code below this line

if (n <= 0) {

return 0;

}

return arr[n - 1] + sum(arr, n - 1);

// Only change code above this line

}

This was my solution to the lesson and I’ve been watching videos on how recursion works, and I’m understanding how simpler and different forms of recursion work but the array in this function honestly has me stumped. I’m having trouble understanding what exactly is happening to get the return of 2.

I hate to ask somebody to basically spoon-feed me information but while I can use the function I would very much appreciate a more thorough explanation possibly something step-by-step.

I’m sorry if i am writing too much this is my very first time asking for help in a forum setting.

when the recursive function is called I get that its
sum([2, 3, 4], 1) so would it then be :
arr[2] + sum([3, 4], 0)?

and then since the n = 0 the base case condition is met and our function doesn’t get called again, right ?

this means to get the sum of the first one elements of the array, as the second argument is 1, so we have return arr[n - 1] + sum(arr, n - 1);, substituting values it is return arr[0] + sum([2, 3, 4], 0) (remember that n is 1, so n-1 is 0) so it’s return 2 + sum([2, 3, 4], 0);, this second function returns 0 because of the if statement, so you have return 2 + sum([2, 3, 4], 0); becoming return 2 + 0, so return 2

1 Like

OK thank you very much for that explanation, I can see what was confusing me was that in other forms of recursion when the function is first called its usually just the base value of the variable and here it does have a -1 attached to it and I was not applying that.