# Replacing Loops using Recursion

Tell us what’s happening:
can any one tell me whats happening here.
@caryaharper

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

// Only change code above this line
}

sum([1, 2] , 2);
console.log()
``````
``````  **Your browser information:**
``````

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

Challenge: Replace Loops using Recursion

In your `if` you should be returning `0`.

The recursion in this case can be a bit confusing as it seems a bit backwards compared to a loop, but written out it kinda looks like this:

``````/*

sum([1,2], 2) returns sum(arr, 2 - 1) + arr[2 - 1]
sum(arr, 1) returns sum(arr, 1 - 1) + arr[1 - 1]

this sum(arr, 1 - 1) returns 0 so sum(arr, 1) returns
0 + arr == 1

therefore

sum([1,2], 2) returns sum(arr, 1) + arr
and we now know that sum(arr, 1) returns 1 so
sum([1,2], 2) returns 1 + arr or 1 + 2 == 3

*/
``````

As you can see you have to get all the way to the bottom in order to start building your answer up. Doing recursion in the way above will quickly cause a `RangeError` for exceeding the maximum call stack size so do be careful if you are trying to use this method over a loop.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.