Array Max & Min in JavaScript
Math.max(...arr). Empty array: do not spread it, you get -Infinity.
BeginnerArray ProgramsExample 1 of 6
array-max-min.js
1// Method 1: Using Math.max and Math.min with spread operator2let numbers = [10, 5, 20, 15, 8, 25];34let max = Math.max(...numbers);5let min = Math.min(...numbers);67console.log("Array:", numbers);8console.log("Maximum:", max);9console.log("Minimum:", min);1011// Method 2: Using for loop12function findMaxMin(arr) {13 if (arr.length === 0) return { max: null, min: null };1415 let max = arr[0];16 let min = arr[0];1718 for (let i = 1; i < arr.length; i++) {19 if (arr[i] > max) max = arr[i];20 if (arr[i] < min) min = arr[i];21 }2223 return { max, min };24}2526let result = findMaxMin([10, 5, 20, 15, 8]);27console.log("\nUsing loop:", result);2829// Method 3: Using reduce30function findMaxMinReduce(arr) {31 return arr.reduce((acc, num) => {32 acc.max = Math.max(acc.max, num);33 acc.min = Math.min(acc.min, num);34 return acc;35 }, { max: arr[0], min: arr[0] });36}3738console.log("\nUsing reduce:", findMaxMinReduce([3, 7, 2, 9, 1]));3940// Method 4: Using sort41function findMaxMinSort(arr) {42 let sorted = [...arr].sort((a, b) => a - b);43 return {44 min: sorted[0],45 max: sorted[sorted.length - 1]46 };47}4849console.log("\nUsing sort:", findMaxMinSort([12, 4, 8, 19, 3]));
Output
Array: [ 10, 5, 20, 15, 8, 25 ]
Maximum: 25
Minimum: 5
Using loop: { max: 20, min: 5 }
Using reduce: { max: 9, min: 1 }
Using sort: { min: 3, max: 19 }What's going on
Math.max(...arr) is the short one. A loop is the one you can write on a whiteboard.
Math.max() with no args is -Infinity. Empty array plus spread is that bug.