0

For the code below I wonder why the the last "0" after "(arr[i] || 0)" is needed?

I aknowledge that without this "0" the code doesnt run as intended, but I do not actually get what that last "0" after "," makes it work.

Could someone explain it?

function addTogether (...arrays) {
    let result = [];
    let arrayLength = Math.max(...arrays.map(array => array.length));
    for (let i = 0; i < arrayLength; i++) {
      result.push(arrays.reduce((sum, arr) => sum + (arr[i] || 0), 0));
    }
    return result
  }
  
  test(addTogether([1, 2, 3], [4, 5], [6]), [11, 7, 3]);
Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
Julio
  • 1
  • 1
  • 5
    If `arr[i]` is `null` or `undefined`, it ensures a number is returned (`0`)....After re-reading, it looks like you are referring to the last `0` in `sum + (arr[i] || 0), 0` ?? – 001 Nov 09 '21 at 13:06
  • 1
    The `0` after the comma is the initial accumulator value for `.reduce()`. – Pointy Nov 09 '21 at 13:07
  • It should be noted by those who closed this question that the OP was **not** asking about the 0 in `|| 0`, but about the 0 in argument position 2 of the `.reduce()` call. – Pointy Nov 09 '21 at 13:13
  • Thanks, it is very clear now! – Julio Nov 09 '21 at 13:17

0 Answers0