0

I'm wondering if there are any benefits for using reduce over the for loop. (except for it's shorter)

Let's take, for example, the sum function.

function sum(arr) {
   return arr.reduce((acc, current) => acc + current, 0);
}

Or with for.

function sum(arr) {
  let total = 0;
  for (let i = 0; i < arr.length; i++){
    total += arr[i];
  }
  return total;
}
undefined
  • 6,366
  • 12
  • 46
  • 90
  • `for-loop` it's always faster in comparison to anything, period! :-).. The benefit of `reduce`: readability. – Ele Jan 27 '18 at 20:27

1 Answers1

0

Aside from brevity, as you mentioned, it also helps in readability: reduce is explicit in what it does whereas a for loop is generic.

Performance wise reduce is generally slower, especially if using an anonymous function.