Basic JavaScript: Replace Loops using Recursion code example
Example: replace loops using recursion
//Write a recursive function, sum(arr, n), that returns the sum of the first n elements of an array arr.
/* 1) sum([1], 0) should equal 0.
2) sum([2, 3, 4], 1) should equal 2.
3) sum([2, 3, 4, 5], 3) should equal 9. */
function sum(arr, n) {
if(n <= 0) {
return 0;
} else {
return sum(arr, n - 1) + arr[n - 1];
}
}