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 operator
2let numbers = [10, 5, 20, 15, 8, 25];
3
4let max = Math.max(...numbers);
5let min = Math.min(...numbers);
6
7console.log("Array:", numbers);
8console.log("Maximum:", max);
9console.log("Minimum:", min);
10
11// Method 2: Using for loop
12function findMaxMin(arr) {
13 if (arr.length === 0) return { max: null, min: null };
14
15 let max = arr[0];
16 let min = arr[0];
17
18 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 }
22
23 return { max, min };
24}
25
26let result = findMaxMin([10, 5, 20, 15, 8]);
27console.log("\nUsing loop:", result);
28
29// Method 3: Using reduce
30function 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}
37
38console.log("\nUsing reduce:", findMaxMinReduce([3, 7, 2, 9, 1]));
39
40// Method 4: Using sort
41function 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}
48
49console.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.