Replace Loops using Recursion project

I am really stuck on the Basic JavaScript: Replace Loops using Recursion project.
It even fails after I copy and paste the solution provided, so please give me a hint as to what is wrong and how I can fix it.
The solution code provided is:
function sum(arr, n) {
if (n <= 0) {
return arr[0];
} else {
return sum(arr, n - 1) + arr[n];
}
}
The tests say that “sum([1], 0) should equal 0”, but I don’t see how that can happen from the above code. It says that if n <= 0 then return arr[0], which is 1 ([1])?
Please help!

Oh yeah I just went through that problem and tried the solution they give. It definitely doesn’t work. The reason is that the question is asking you to sum n number of items in the array and for some reason the solution given just plops n into the array when it should be arr[n-1] I think there might be another issue with the solution but I can’t recall I will go check. Let me know if that was enough to get you unstuck :slight_smile:

Ok so I went back to check it again to see what the other problem with their solution code is and here is what I found:

the line that says: return arr[0]; causes a double up on the value in the first spot of the array. it should instead be: return 0;

This fixes it. The code I used is as follows:

function sum(arr, n) {

if (n <= 0) {

return 0;

} else {

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

}

}

var myArray = [1,2,3,4,5,6,7];

console.log(sum(myArray, 3));

The last two lines I’ve added so I could play with the code to see what it’s doing. If you’re not doing this I would recommend it. I use the console.log to see what is happening. You can also put them in loops and other spots in your code to send yourself messages to the output box to make sure your loops and stuff are flowing the way you intend. Good luck and let me know if that wasn’t clear.

Thanks for the replies. I changed the return from ‘arr[0]’ to ‘0’ as a work around thinking I had something else wrong, but I’m glad it is supposed to be there. All good now, but I think I’ll have to go over it a few times to make sure I understand the solution.

The hint/solutions topic has not been updated to match the recent changes to this challenge. We apologize for any confusion this may have caused.