The following simple function takes in an array and a number, and essentially outputs that array's length * the number specified.
function sum(arr, n) {
if (n <= 0) {
return 0;
} else {
return sum(arr, n - 1) + arr[n - 1];
}
}
If we call the following: sum([2, 3, 4, 5], 3), we correctly get 9 as the final output value.
For exmaple:
function sum(arr, n) {
if (n <= 0) {
return 0;
} else {
return sum(arr, n - 1) + arr[n - 1];
}
}
console.log(sum([2, 3, 4, 5], 3))
Not sure I understand what is going on here though. Where is this final value getting stored? I can see that calling the function in the function and using decreasing values in each instance is essentially replacing a for loop, but without additional context I'd expect the output to either always return 0 or for the function to not work at all.
What hidden aspects are coming into play to make this return that desired value?
returnstatement