Tell us what’s happening:
Describe your issue in detail here.
I did this challenge and watched a video to better understand recursion. From my understanding recursion is calling the function itself inside it’s function. I did the breakdown on how this work if I call the function sum into my own words. However, I still don’t get how it adds the number 4, 3, 2 which are the values of the index 2,1,0 because if I convert the code
return sum(arr, n -1) + arr[n-1];
it will be like this
sum[2,3,4,5], 2 + 4;
sum[2,3,4,5], 1 + 3;
sum[2,3,4,5], 0 + 2;
right?
but how does it add up?
or
sum[2,3,4,5], 2 = 4;
sum[2,3,4,5], 1 = 3;
sum[2,3,4,5], 0 = 2;
Like, how does this recursive function works inside?
**Your code so far**
function sum(arr, n) {
// Only change code below this line
if (n <= 0) {
return 0;
} else {
return sum(arr, n -1) + arr[n-1];
}
// Only change code above this line
}
console.log(sum([2, 3, 4, 5], 3))
**Your browser information:**
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36
Challenge: Replace Loops using Recursion
Link to the challenge: