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];
}
}
In a recursive function, you want to start with the leaving return statement, which in this case is when the array is empty.
// if the array is empty, return the total.
if(!arr.length) return total;
If we have more items, pop the top item and add it to the total. Popping returns the last item and removes it from the array.
total += arr.pop();
Then we return the recalled function and pass it the updated parameters.
return sum(arr, total);
function sum(arr = [], total = 0) {
if (!arr.length) return total;
total += arr.pop();
return sum(arr, total);
}
console.log(sum([1, 2, 3]))