javascriptbeginner10 minutes

Fix the Bug in Array Sum Function

The provided JavaScript function is supposed to sum all numbers in an array, but it contains bugs. Your task is to identify and fix the bugs so the function correctly returns the sum of the array elements.

Challenge prompt

Below is a JavaScript function intended to sum all numbers in an array. However, the function is returning incorrect results or errors. Fix the bugs in the function to make it return the correct sum of any numeric array passed to it.

Guidance

  • Check the function parameters and ensure they are used correctly.
  • Look at how the loop iterates through the array elements.
  • Make sure the sum variable is initialized properly before use.

Hints

  • Remember to initialize the sum variable before adding values to it.
  • Check that the for loop condition correctly iterates over the array indices.
  • Ensure the function returns the computed sum after the loop.

Starter code

function sumArray(arr) {
  let sum = 0;
  for (let i = 1; i <= arr.length; i++) {
    sum += arr[i];
  }
  // missing return statement
}

Expected output

sumArray([1, 2, 3, 4]) // 10 sumArray([10, -5, 7]) // 12 sumArray([]) // 0

Core concepts

loopsarraysfunction return valuesvariable initialization

Challenge a Friend

Send this duel to someone else and see if they can solve it.