Question for :Replace Loops using Recursion

I understand recursion(I thought) but in this code why does it return 2? I know 2 is the first index of the array and that is arr[n-1] but because the last thing that is returned is the 0 shouldn’t that kick out of the function as 0 as the return? Thanks

``````let num = [2, 3, 4];
let n = 1;
function sum(arr, n)  {
if(n === 0) {
return 0;
}  else   {
return sum(arr, n-1) + arr[n-1];
}
}
sum(num, n);
``````

Ok, I will try to explain it. So in your code n is 1, so for arr[n - 1] it would be arr[1 -1], and would add arr[0], this does not change the n, the n only decreases by one after it has added arr[0], and the it decreases on sum(arr, n-1). Then n becomes 0 so it stops the recursion.

What i don’t understand is that on the 2nd go around(After it calls itself) it checks n and n is now equal to 0 so the if condition is now true so then it calls the return 0; So I wondering why it the just returns 2 when the last return was 0?

try looking at the function execution with this tool:

http://pythontutor.com/javascript.html#mode=edit

1 Like

What a great tool! I will def use it in the future but using it only makes me more confused because its doing exactly what I thought the code would do. Like if you put a string instead of the 0 , it concatenates the string with the 2 and returns both? How is that, I thought if it hit a return it would kick out of the function, how is the 2 still getting returned?

because you actually have two functions being called - that’s the point of recursion

`sum([2,3,4], 1)` calls and use the returned value from `sum([2,3,4], 0)`, so the second one returns 0

but the first one returns `sum(arr, n-1) + arr[n-1]`, so `sum(arr, 0) + arr[0]`, so `0 + 2`

1 Like

If you log key values you can ‘look’ into the function and see what is happening.
n=1; didn’t read all the elements in the array only arr[n-1] // 2

``````let num = [2, 3, 4];
let n = num.length;
function sum(arr, n)  {
if(n === 0) {
return 0;
}  else   {
console.log('current arr[n]:',arr[n]);
return sum(arr, n-1) + arr[n-1];
}
}
console.log(sum(num, n));
// prints :
// current arr[n]: undefined
// current arr[n]: 4
// current arr[n]: 3
//
// 9``````