javascriptbeginner10 minutes
Fix the Function to Calculate the Sum of an Array
There's a simple bug in the function that calculates the sum of numbers in an array. Your task is to identify and fix the issue so that the function returns the correct sum.
Challenge prompt
The function sumArray is supposed to return the sum of all elements in the given array. However, the current implementation returns an incorrect result. Identify the problem in the code and fix it so it works correctly for any array of numbers.
Guidance
- • Check how the accumulator variable is initialized and updated inside the loop.
- • Make sure the loop iterates over all elements in the array correctly.
Hints
- • Remember that the accumulator should start at 0 when summing numbers.
- • Verify that the loop condition allows processing every element in the array.
Starter code
function sumArray(arr) {
let sum = 1;
for (let i = 0; i <= arr.length; i++) {
sum += arr[i];
}
return sum;
}Expected output
sumArray([1, 2, 3, 4]) // returns 10
Core concepts
loopsvariablesfunctionsarray traversal
Challenge a Friend
Send this duel to someone else and see if they can solve it.