Tell us what’s happening:
Describe your issue in detail here.
**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
}
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36
Challenge: Basic JavaScript - Replace Loops using Recursion
Thank you turns out I only needed to return 0. So I need to return 0 in terms of itself which is 0(base case)? Also i dont understand the recursion sum(arr, n - 1) + arr[n - 1] does it mean for e.g 5 - 6, 5 - 6, 5 - 6 or 1 + 1, 1 + 1 , 1 + 1 ?
Remember what the function is doing. It adds the first n numbers of the array arr. So you can’t know what the sum of [1,2,3] is unless you know what the value of n is.
So, what the condition or code (arr, n -1) and arr[n -1] is constant unless the parameters are different? also will my initialized value always return the same value initialized?
I think I understand it a little better so ill only use recursion when n is less than and equal to 0? in cases where its more than 0 it will result in an infinite loop? I need to know this because I dont know in what other instances ill have to use it, maybe when i need to divide? or subtract?