Hacker News new | ask | show | jobs
by ahoge 3901 days ago

    function sum(array) {
      return array.reduce((a, b) => a + b);
    }
With a loop:

    function sum(array) {
      let acc = 0;
      for(let val of array) {
        acc += val;
      }
      return acc;
    }
1 comments

What's the value of sum for an empty array in your example?
The reduce one needs an initial value of 0 for that to work. Then both versions will return 0 if the array is empty.

    array.reduce((a, b) => a + b, 0);