Recursion Help!

Tell us what’s happening:

Hey guys,
I have passed this challenge somehow, but I didn’t understand the logic behind it.
Can anyone please explain it to me?

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
}

console.log(sum([1,2,3], 2));

Your browser information:

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

Challenge: Replace Loops using Recursion

Link to the challenge:

Okay, to break it down, if n is 0, what does the function return?

To put it another way and use the example at the end, what is the value of sum([1,2,3], 0)?


So if n is 0, the return value is 0.

So what if n is 1: sum([1,2,3], 1)?

n is not <= 0, so

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

So n - 1 is 0. sum([1,2,3], 0 is 0. So that says return 0 + 1, so 1.

So the return value of sum([1,2,3], 1) is 1.


So what if n is 2?

n is not <= 0, so

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

So n - 1 is 1. sum([1,2,3], 1) is 1. So that says return 1 + 2, so 3.

When trying to understand loops and/or recursion, it can be helpful to track the values at each step. Here’s an example: