const numbers = [2, 8, 82, 51, 6];
const largestNumber = Math.max(...numbers);
const smallestNumber = Math.min(...numbers);
console.log('largestNumber is', largestNumber);
console.log('smallestNumber is', smallestNumber);
Output:
largestNumber is 82
smallestNumber is 2
- Here, spread operator converts an array into individual arguments.
- So Math.max and Math.min expect a list of arguments, not an array directly.
- For small and medium size arrays Math.max and Math.min are the simplest and most effective way.
- For Large Arrays we need to use Array.reduce() for better performance.
- And most importantly Math.max and Math.min works only for array of numbers.