javascriptbeginner10 minutes
Fix the Bug in the Function That Calculates the Sum of an Array
This challenge involves debugging a simple JavaScript function that is intended to sum all numbers in an array but currently returns an incorrect result.
Challenge prompt
The function sumArray is supposed to take an array of numbers and return their total sum. However, it contains a bug that causes it to return the wrong output. Fix the bug so that the function returns the correct sum of all numbers in the input array.
Guidance
- • Check the loop structure and ensure all elements are being processed.
- • Verify the variable used to accumulate the sum is properly initialized and updated.
Hints
- • Look carefully at the loop condition, it might be off by one.
- • Make sure you are adding the numbers to the sum variable, not assigning.
Starter code
function sumArray(arr) {
let sum = 0;
for (let i = 0; i <= arr.length; i++) {
sum = arr[i];
}
return sum;
}
console.log(sumArray([1, 2, 3, 4]));Expected output
10
Core concepts
loopsvariablesarraysbasic debugging
Challenge a Friend
Send this duel to someone else and see if they can solve it.