How does this function work?

Tell us what’s happening:
Guys, guys ! I really don’t understand how this algorithm comes up with these results !
Can someone ELI5 all the steps the program go through to return the number 63, with
this array values :

sum([5,10,15,18,5,1,9], 7);

I’m really stuck with this program, I have really no clue what it does !

Pliz send help. Thank you.

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([5,10,15,18,5,1,9], 7));

= 63

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0.

Challenge: Replace Loops using Recursion

Link to the challenge:

this function accepts two arguments, an array, and a number telling to sum the first n-th numbers of the array
so, summing the first 7 numbers of that array, we have 5+10+15+18+5+1+9 which makes 63

recursion means calling the function inside itself with different arguments
so, inside sum([5,10,15,18,5,1,9], 7); we use sum([5,10,15,18,5,1,9], 6) and sum to it the 7th number - so what happens is that the 54 comes from the function call inside, and to return the result 9 is added to it, and then returned

where does the 54 comes from?
inside sum([5,10,15,18,5,1,9], 6) there is sum([5,10,15,18,5,1,9], 5) + 1

and so on

you can try seeing the execution with this tool:

you could also take a look at this throurough explanation of recursion: