Tell us what’s happening:
So this is the first topic I’ve struggled with in hours of study on the site, and I feel it may be due to the brief explanation given regarding “return 0” or “return 1” in this activity.
In prior examples, exiting a function by typing “return “hello world!”” would return an answer of “hello world!”. But now we are returning 0, however the sum is somehow returning with it. This is confusing.
Why does return 0 return more than the number 0? It somehow includes the sum of the work done as well. Where is the final step that says “take the 0 and then add on all the previous work done”? To me, return 0 should just send back a 0.
What’s going on?
Thanks in advance.
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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36
.
Challenge: Replace Loops using Recursion
Link to the challenge: