javascriptbeginner10 minutes

Refactor Imperative Sum Calculator to Clearer Functional Code

Improve the readability and maintainability of a simple JavaScript function that calculates the sum of numbers in an array by refactoring it from a verbose imperative style to a clean and concise functional style.

Challenge prompt

You are given a function that calculates the sum of elements in an array using a traditional for loop with extra variables. Refactor this function to make it simpler and more readable without changing its behavior. Use JavaScript best practices to improve the code quality, clarity, and conciseness.

Guidance

  • Focus on simplifying the function while keeping the output identical for any input array.
  • Consider replacing the loop and accumulator variables with a more functional approach.
  • Make sure the function still returns the correct sum for both empty and non-empty arrays.

Hints

  • Look into the array method 'reduce' for summing elements in a functional style.
  • Avoid unnecessary variable initializations if they don’t improve clarity.
  • Keep your function signature and return behavior unchanged.

Starter code

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

Expected output

sumArray([1, 2, 3, 4]) // 10 sumArray([]) // 0 sumArray([10, -5, 20]) // 25

Core concepts

refactoringfunctional programmingarray methodscode readability

Challenge a Friend

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