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
Link to the challenge: