I have a simple recursion function that returns the sum of the first n elements of the array. I’m a little bit struggling with understanding: when the function calls itself through return return sum(arr, n-1) + arr[n-1];
what actually this sum(arr, n-1)
does as it is not added to the final sum eventually and why it’s not been calculated.
Here’s the whole function, really appreciate any explanation.
function sum(arr, n) {
if (n === 0) {return 0}
else if (n >= 1) {
return sum(arr, n-1) + arr[n-1];
}
}