Recursion Explanation

Tell us what’s happening:
I got the correct answer for this exercise, however, i don’t fully understand what is happening on this line of my code. ```

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

**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 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0.

Challenge: Replace Loops using Recursion

Link to the challenge:

Hi swonggzz,
I had to spend some time figuring out the recursion section too, because the examples didn’t go over the call stack in their explanation (which, for a basic section they should, imo, because I can imagine that it could leave beginners more confused) . Anyway, here’s an image I made of a recursive function to help me get my brain around it. It’s not the same one, but maybe it will still be helpful (if someone notices anything wrong let me know, I don’t want to make people even more confused)

This is the line that jumps down the rabbit hole of recursion. Your sum function will return the result of the addition on the right. But the addition can’t be calculated until sum(arr, n - 1) returns a value, so it waits until it has all the pieces. The important thing to remember with recursion is that sum arr, n - 1) is a independent instance of the sum function. It’s not looping back to the top.