Recursion and return

Hey everyone I am doing the javascript section in regards to recusrion. I am having an issue understanding it and would like to see if anyone can offer clarification on it. This is the task - Write a recursive function, sum(arr, n), that returns the sum of the first n elements of an array arr.

This is the answer - ‘’

``````function sum(arr, n) {
if(n <= 0) {
return 0;
} else {
return sum(arr, n - 1) + arr[n - 1];
}
}
``````

Now correct me if im wrong but I understand the first part of if(n <= 0) as this is meant to stop the loop. It returns 0 because the 0 would be added to the final sum i believe and if it was multiplication it would return 1 because you can’t properly multiply by 0?

now as for the else statement if the arr = [1,2,3,4] and n = 3 then the first loop would end up returning sum(arr, 2) + 3. Because 3-1 = 2 and arr[2] is 3. now the second loop would return sum(arr, 1) + 2. I am curious what happened to the + 3 we previously had is it just dropped because the return statement doesn’t involve it? Also, now that n = 1 the loop would no longer execute so then im left with sum(arr, 1) + 2. And this is when it stops making any sense to me. I dont know what to do with that nor do i understand how sum([2, 3, 4], 1) would be equal to 2 according to freecodecamp. What is happening here in the end and how does sum([2, 3, 4], 1) = 2?

Challenge: Replace Loops using Recursion

`sum(arr, 3)` is that same as
`sum(arr, 2) + 3` is the same as
`sum(arr, 1) + 2 + 3` is the same as
`sum(arr, 0) + 1 + 2 + 3` is the same as
`0 + 1 + 2 + 3` is the same as
`6`

That’s basically what’s happening.

1 Like

n is representing the first n items. Think about it in terms of array indexes.

What is the index of the first array item, it is 0. Ok so what number is located at index arr[0]? It is 2. There’s nothing else to sum it with because the second parameter was 1. So it just returns 2 in that case.

For `sum([2, 3, 4, 5], 3)`

we are to sum the first three items. That is what the three means there. We are not adding it in.

How would we programmatically access the first 3 items in an array? By their indexes, right? So what are the indexes? 0, 1, 2 respectively.

arr[0] is 2
arr[1] is 3
arr[2] is 4

those are the first 3 items. What is their sum? 9

This link has a more detailed explanation…