 # I can't understand this in the recursion lesson

Hello! I can’t understand what arrays has to do with the recursion lesson. I do understand recursion though. Heres the line I can’t figure out.

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

I don’t understand the last half of that line which is “+ arr[n - 1];”
I don’t understand how to even call this function or what it really does at this point. I’ve read the lesson a million times and I’ve watched a bunch of Youtube videos but I can’t to save my life figure out what free code camp means.

" Write a recursive function, `sum(arr, n)` , that returns the sum of the first `n` elements of an array `arr` ."

Those are the instructions. I don’t understand those instructions at all and I can’t understand whats the goal of code even is from the instructions.

Thank Youuuu!

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

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15`

Challenge: Replace Loops using Recursion

`arr` and `n` are both values passed into the function. I’m assuming you understand array notation? So if `arr` is an array and `n` is a number then `arr[n-1]` should be pretty straight forward, it’s the value at index `n-1` in the array. So if you called the function as:

`sum([1,2,3,4], 4)`

Then what would `arr[n-1]` work out to?

`arr[4-1]` == `arr` == `4`

So `+ arr[n - 1]` is adding the value of `arr[n-1]` to the value returned by the recursive call `sum(arr, n - 1)`.

1 Like

thanks so much! this was ultimately the answer to my confusion!