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 ?