constarray=[-1,10,30,45,5,6,89,17];// `(previousValue, currentValue, index, array) => nextValue`// Notice how all data (`currentValue`, `index`, `array`) // associated with the array being folded is "bunched up" // to the right/end of the parameter list.constselectMax=(previous,value)=>value>previous?value:previous;// 1. `initialValue` is optional without it `array[0]` // becomes the `initialValue` and processing starts // at `array[1]`// 2. Without `initialValue` an empty array will cause:// `TypeError: Reduce of empty array with no initial value`// So empty arrays have to be handled separatelyconstmaxValue=array.length>0?array.reduce(selectMax):undefined;console.log(maxValue);
Technically using Number.NEGATIVE_INFINITY would be logically improper if the array had no elements,
While I agree that is exactly what happens with Math.max():
Put differently:
While I agree that is exactly what happens with
Math.max()
:Perhaps that is consistent with
i.e. return a value that is "a number" put invalidates most following numeric operations without forcing the script to stop (throw an error).