DEV Community

Discussion on: How many way to find max number in array on Javascript.

Collapse
peerreynders profile image
peerreynders

Put differently:

const array = [-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.
const selectMax = (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 separately
const maxValue = array.length > 0 ? array.reduce(selectMax) : undefined;
console.log(maxValue);
Enter fullscreen mode Exit fullscreen mode

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():

console.log(Math.max()); // -Infinity
Enter fullscreen mode Exit fullscreen mode

Perhaps that is consistent with

console.log(typeof NaN); // "number"
console.log(typeof Number.NEGATIVE_INFINITY); // "number"
Enter fullscreen mode Exit fullscreen mode

i.e. return a value that is "a number" put invalidates most following numeric operations without forcing the script to stop (throw an error).