# Recursion: Replace Loops using Recursion Explanation

Tell us what’s happening:
Can someone help me to understand what is going on in the else return statement to pass these two tests:
`sum([2, 3, 4], 1)` should equal 2.
`sum([2, 3, 4, 5], 3)` should equal 9.
I’m having a very hard time wrapping my head around this problem.

``````
function sum(arr, n) {
// Only change code below this line
function sum(arr, n) {
if (n <= 0) {
return 0;
} else {
return sum(arr, n - 1) + arr[n-1];
}
}
// Only change code above this line
}

``````

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

Challenge: Replace Loops using Recursion

you have a function definifion inside a function definition, that’s not what you want

the outer function when called just return undefined, the inner one is never called

1 Like

Oops just realized I entered an extra ‘}’ to the end of the code but this is the solution that was provided for this problem… Maybe there’s an error and that’s why I’m so confused,?

you have twice the function definition, the outer one doesn’t have a return statement, so it returns undefined

2 Likes

Must have been from copy/paste, can you help with what this return stack is returning?
`return sum(arr, n - 1) + arr[n-1];`

hi there…guys where do you get this sum([2,3,4], 1)…the exemple doesnt exist on my page and I feel like I learn in blind mode…somehow I managed to guess the code and when I hit test, its starts to tell me :
sum([1], 0) should equal 0.
sum([2, 3, 4], 1) should equal 2…
from where???etc…I cant see anywhere on my page the example …!!!

and this is happening with every lesson I passed until now…how can I understand something without having the example?..thx

1 Like

The test cases are listed on the left side of your screen after the challenge description.

Here is a screenshot of where they are on mobile.

2 Likes