Emmanuel Akinfulubi

JavaScriptBasic

Find the min and max of an array in JavaScript

Beginner · 3 min read

The highest score in a class, the cheapest flight, the coldest day of the month: finding the smallest and largest value in a list is one of the most common jobs in programming. JavaScript has Math.min and Math.max built in, but they don't take an array directly, and they give surprising answers for an empty list.

In this tutorial you will find the lowest and highest marks in an array two ways: with the spread syntax and with reduce. You will also find out why Math.min() with nothing in it gives Infinity. You need to know what an array and a function are.

Math.max takes separate values

Math.max and Math.min take any number of separate values, separated by commas:

JavaScript

console.log(Math.max(67, 45, 92)); // 92
console.log(Math.min(67, 45, 92)); // 45

Give them an array instead, and they try to turn the whole array into one number, which fails:

JavaScript

console.log(Math.max([67, 45, 92])); // NaN

The spread syntax

Three dots in front of an array, ...marks, unpack its items into separate values. So Math.max(...[67, 45, 92]) is the same as writing Math.max(67, 45, 92).

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

54 Smallest and largest in a list

easy

Find the smallest and largest number in an array. Also exercise 18, there picking the largest of three named values; here the list can be any length, which changes the tool.

Stuck? Three hints, smallest first
  1. 1. Math.max takes separate arguments, not an array. Spread the array into it.
  2. 2. Spreading has a limit — around 100,000 arguments, depending on the engine — so a reduce is safer for very long lists.
  3. 3. Math.min() with no arguments has to answer something. Work out what, and why that answer is the right one.

Step 1: spread the array

Step 1

const marks = [67, 45, 92, 58, 92, 12];
const highest = Math.max(...marks);
const lowest = Math.min(...marks);
console.log(highest, lowest); // 92 12

The duplicate 92 doesn't matter: the largest value is still 92.

This is the version to use for everyday lists. It has one limit. Each item becomes a separate argument to the function, and an engine can only accept so many. In Node.js, spreading an array of a million numbers into Math.max throws RangeError: Maximum call stack size exceeded.

Step 2: reduce, for lists of any size

reduce walks a list and carries one value along, here "the smallest so far". At each item it keeps whichever is smaller:

Step 2

const marks = [67, 45, 92, 58, 92, 12];
const smallest = (list) => list.reduce((lo, n) => (n < lo ? n : lo), Infinity);
const largest = (list) => list.reduce((hi, n) => (n > hi ? n : hi), -Infinity);
console.log(smallest(marks), largest(marks)); // 12 92

n < lo ? n : lo means "if n is smaller, keep n, otherwise keep lo". There is no limit on the list's size, because the values are never passed as separate arguments.

Step 3: why start at Infinity?

The second argument to reduce, Infinity, is the starting value for "smallest so far". It has to be bigger than any real number, so that the first item always replaces it. Infinity is exactly that.

Now look at what Math.min and Math.max give with nothing at all:

Step 3

console.log(Math.min()); // Infinity
console.log(Math.max()); // -Infinity

This looks odd, but it is the same idea. The smallest of nothing must lose to every real number you add later, and Infinity is the only value that does. The reduce version agrees for an empty list:

JavaScript

const smallest = (list) => list.reduce((lo, n) => (n < lo ? n : lo), Infinity);
console.log(smallest([])); // Infinity

If an empty list is possible in your app, check for it and show "no marks yet" rather than Infinity.

Step 4: one bad value spoils the answer

Math.max converts every value to a number first. Text that isn't a number becomes NaN, and then the answer is NaN:

JavaScript

console.log(Math.max(1, 'lagos', 3)); // NaN

No error is thrown, so clean the list before you look for the highest value.

The full solution

The answer panel has both versions, prints the highest and lowest marks, confirms they agree, and shows the empty and bad-value cases. Some checks compare with === Infinity and expect true, because turning Infinity into text for a comparison gives null and could hide a wrong answer. Press Run to see the output.

The answer

const marks = [67, 45, 92, 58, 92, 12];

const highest = Math.max(...marks);
const lowest = Math.min(...marks);

// Safe for a list of any size, and clearer about the empty case.
const smallest = (list) => list.reduce((lo, n) => (n < lo ? n : lo), Infinity);
const largest = (list) => list.reduce((hi, n) => (n > hi ? n : hi), -Infinity);

console.log('marks   ->', marks);
console.log('highest ->', highest, 'lowest ->', lowest);
console.log('spread and reduce agree:', highest === largest(marks));
console.log('Math.min() with nothing ->', Math.min(), '<- so any real number beats it');
console.log('one bad value ->', Math.max(1, 'lagos', 3));

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the highest mark', highest, 92);
test('the lowest mark', lowest, 12);
test('reduce gives the same answers', [smallest(marks), largest(marks)], [12, 92]);
test('Math.min() with no arguments is Infinity', Math.min() === Infinity, true);
test('and Math.max() is minus Infinity', Math.max() === -Infinity, true);
test('careful: JSON turns Infinity into null', JSON.stringify(Math.min()), 'null');
test('an empty list falls out to the same starting value', smallest([]) === Infinity, true);
test('one non-number poisons the whole answer', Number.isNaN(Math.max(1, 'lagos', 3)), true);

Math.min() answering Infinity is not a quirk, it is the only consistent answer: the smallest of nothing must lose to every real number, and that is what Infinity does. It also makes Infinity the correct seed for a reduce.

Two traps worth carrying away. Math.max(...marks) passes one argument per element, so a list of a million numbers can blow the call stack where a reduce would not. And because these compare with < on the results of coercion, a single 'lagos' in the list makes the answer NaN silently. Note the assertion style: === Infinity against true, because JSON.stringify(Infinity) is "null" and a direct comparison would pass against null too.

Common mistakes

  • Passing the array straight in. Math.max(marks) is NaN. Spread it: Math.max(...marks).
  • Starting reduce at 0. For "smallest", 0 beats every positive mark, so a list of [67, 45] reports 0. Start at Infinity.
  • Ignoring the empty list. Math.min() is Infinity, which looks strange on a results page. Handle the empty case yourself.

Try it yourself

  1. Return both values at once as { lowest, highest } from a single reduce.
  2. Find the student with the top mark from [{ name: 'Ada', mark: 67 }, { name: 'Tunde', mark: 92 }].
  3. Print the range of the marks: the highest minus the lowest.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.