Tell us what’s happening:
I don’t really need help with making code, but it’s unclear how the function recurses. I’ve put a bunch of console.log() in some places to track the recursion, but nothing happened (although recursion did happen). Would anyone explain why and tell if there’s in general a way to track recursion?
Your code so far
function sum(arr, n) {
// Only change code below this line
if (n<=0){
return 0;
console.log('rec');
}else{
return sum(arr, n-1)+arr[n-1];
console.log('ursion');
}
// Only change code above this line
}
console.log(sum([2, 3, 4], 1));
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36.
Your log’s didn’t trigger because they are below the return statements : ) I’d try moving them up above the returns. You might also want to print n on each function call to help you see what’s going on.
Recursion is a self looping technique when the base condition in every iteration is (n-1).
This looping technique require the use of call-stack, which means (keeping track when a function is called and in what order).
For example, if you want to add from the number 10 - 1. You would keep 10 in your mind, and then the next number would be (10 - 1). So you get 10 + 9, then you get the next number (9-1), so now you get 10 + 9 + 8. You do this until you reach the base condition which is 1.
function sum( from, to ) {
return from + ( from > to ? sum( from - 1, to ) : 0 );
}
I struggled to “get” recursion from this challenge.
For me, the most helpful thing was solving the problem with pen and paper first. And then writing by hand what the function is doing - especially in each loop of the else statement. If I can solve the problem with pen and paper, then the code generally makes more sense to me.