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?
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?