Sum an Array
So far n got smaller. You can recurse over a list the same way: shrink the
array by peeling off the first element each call.
The pattern is "first + rest": add the first element to the sum of everything
after it. The base case is the empty array, which sums to 0.
function sumArray(arr) {
if (arr.length === 0) return 0; // base case: empty sums to 0
return arr[0] + sumArray(arr.slice(1)); // first + sum of the rest
}
sumArray([1, 2, 3]); // 6
arr.slice(1) returns a new array with everything except the first item β so
each call works on a shorter list, marching toward the empty-array base case.
Your task
Write sumArray(arr) that returns the sum of all numbers in arr, using
recursion (no for/while loops).
β‘ 40 XP
π§± Code blocks
Drag a block into the editor, or tap it to drop it in where your cursor is. Add them in order to build your answer.
solution.jsRuns in your browser
Loading editorβ¦
Tests5 to pass
sumArray([1,2,3]) β 6
sumArray([]) β 0
sumArray([10]) β 10
sumArray([5,5,5,5]) β 20
handles negatives
Run your code to check these.