Emmanuel Akinfulubi

JavaScriptDate

Find the earliest and latest date in JavaScript

Intermediate · 4 min read

"First order placed on…", "last login…", "project runs from … to …": finding the earliest and latest date in a list is a small job you will meet in reports and dashboards. JavaScript's Math.min and Math.max can do it in one line each, once you know one extra step.

In this tutorial you will find the oldest and newest date in an array, and then deal with the case that catches people out: an empty list. You need to know what an array is, how to make a date with new Date(year, month, day), and that months count from 0.

Math.min works on numbers

Math.min takes any number of arguments and returns the smallest. Math.max returns the largest:

JavaScript

console.log(Math.min(7, 2, 9)); // 2
console.log(Math.max(7, 2, 9)); // 9

To pass the items of an array as separate arguments, use the spread syntax, three dots before the array: Math.min(...numbers) is the same as writing every number out by hand.

Dates turn into numbers

Math.min turns each argument into a number before comparing. A date turns into its timestamp, the number of milliseconds since 1970. An earlier date has a smaller timestamp, so the smallest number belongs to the earliest date.

But the answer is the number, not the date. You have to turn it back into a date yourself with new Date(number).

To print dates, this tutorial uses iso, which turns a date into YYYY-MM-DD text:

JavaScript

const iso = (d) => d.getFullYear() + '-' +
  String(d.getMonth() + 1).padStart(2, '0') + '-' +
  String(d.getDate()).padStart(2, '0');

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

31 The earliest and latest date in a list

fair

Find the oldest and newest date in an array. Then say what your code does with an empty array, because the obvious version produces something surprising.

Stuck? Three hints, smallest first
  1. 1. Math.min and Math.max take numbers, and a date converts to one.
  2. 2. They return a number, so wrap the result in new Date.
  3. 3. Math.min() with no arguments is Infinity. What is new Date(Infinity)?

Step 1: spread the dates into Math.min

Step 1

const dates = [new Date(2026, 2, 1), new Date(2026, 0, 15), new Date(2026, 1, 20)];
const smallest = Math.min(...dates);
console.log(typeof smallest); // 'number'

It worked, but smallest is a timestamp. If you tried iso(smallest), it would throw, because numbers have no getFullYear method.

Step 2: wrap it back into a date

Step 2

const earliest = new Date(Math.min(...dates));
const latest = new Date(Math.max(...dates));
console.log(iso(earliest)); // '2026-01-15'
console.log(iso(latest));   // '2026-03-01'
console.log(dates.length);  // 3

new Date(timestamp) builds a date for that moment. Now you have real dates you can format. The array itself is untouched: spreading reads the items without changing them.

Step 3: the wrong turn, an empty list

Now pass an empty array:

Step 3

console.log(Math.min());                     // Infinity
console.log(String(new Date(Math.min())));   // 'Invalid Date'

With no arguments, Math.min() returns Infinity. That is its starting value: anything you give it is smaller than infinity. new Date(Infinity) doesn't throw an error. It makes an Invalid Date, a date object whose timestamp is NaN (not a number).

That is the dangerous part. The value looks like a date, so the code carries on. The problem only shows up later, somewhere else, when the page prints "Invalid Date" or a calculation gives NaN.

Step 4: guard the empty case

Check the length first and return null when there is nothing to compare:

Step 4

const earliestOf = (list) => (list.length === 0 ? null : new Date(Math.min(...list)));
console.log(earliestOf([]));          // null
console.log(iso(earliestOf(dates)));  // '2026-01-15'

The ? : is the conditional operator: "if the list is empty, null, otherwise the earliest date". null is a clear "nothing here" that the caller can check for, instead of a broken date.

Step 5: reduce, for long lists

Spreading turns every item into a separate argument. That is fine for tens or thousands of dates, but a very long list, hundreds of thousands of items, can throw an error because there are too many arguments. reduce walks the list one item at a time instead:

Step 5

const viaReduce = dates.reduce((best, d) => (d < best ? d : best));
console.log(iso(viaReduce)); // '2026-01-15'

reduce keeps the best date so far in best. For each date d, if d is earlier, it becomes the new best. < compares dates by timestamp, so this works directly. A bonus: the result is one of the original dates, not a new one built from a number.

Note that reduce with no starting value also fails on an empty list, by throwing a TypeError. So keep the length check either way.

The full solution

The panel finds the earliest and latest dates with Math.min and Math.max, shows that Math.min returns a number, checks the reduce version and a one-item list, and shows the guarded empty case next to the Invalid Date it prevents. Press Run to see the results.

The answer

const iso = (d) => d.getFullYear() + '-' +
  String(d.getMonth() + 1).padStart(2, '0') + '-' +
  String(d.getDate()).padStart(2, '0');

const dates = [new Date(2026, 2, 1), new Date(2026, 0, 15), new Date(2026, 1, 20)];

// Math.min converts each date to a number, so spreading dates straight in works.
const earliest = new Date(Math.min(...dates));
const latest = new Date(Math.max(...dates));

// The empty case, guarded. Without the guard you get Infinity, and
// new Date(Infinity) is an Invalid Date that then spreads silently.
const earliestOf = (list) => (list.length === 0 ? null : new Date(Math.min(...list)));

console.log('earliest:', iso(earliest), '| latest:', iso(latest));
console.log('Math.min() with nothing ->', Math.min(), '-> new Date(Infinity) is', String(new Date(Math.min())));

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 earliest date', iso(earliest), '2026-01-15');
test('the latest', iso(latest), '2026-03-01');
test('Math.min hands back a number, not a date', typeof Math.min(...dates), 'number');
test('a reduce does the same job without spreading', iso(dates.reduce((best, d) => (d < best ? d : best))), '2026-01-15');
test('one date is both earliest and latest', iso(new Date(Math.min(...[new Date(2026, 0, 15)]))), '2026-01-15');
test('the guarded version returns null for an empty list', earliestOf([]), null);
test('because the unguarded one gives an Invalid Date', Number.isNaN(new Date(Math.min()).getTime()), true);
test('and the source array is untouched', dates.length, 3);

Spreading dates into Math.min works because each one converts to its timestamp, and the result has to be wrapped back up in new Date — that is the step people forget, and it produces a number where a date is expected, which then formats as a nine-hundred-billion-something.

The empty-array case deserves the guard. Math.min() is Infinity by definition, and new Date(Infinity) is an Invalid Date rather than an error, so an empty list quietly produces a date-shaped value that fails much later and somewhere else. Also worth knowing: spreading is fine for tens of dates but throws on hundreds of thousands, because each element becomes an argument. Use reduce when the list might be large.

Common mistakes

  • Forgetting new Date(...) around the result. Math.min returns a timestamp, and a big number shows up where a date was expected.
  • Passing the array without spreading. Math.min(dates) gets one argument, an array, which turns into NaN.
  • Not handling an empty list. You get an Invalid Date that fails far from where it was made.

Try it yourself

  1. Write latestOf(list) with the same empty-list guard.
  2. Write dateRange(list) that returns { from, to }, or null for an empty list.
  3. Given an array of orders like { id, placedAt }, find the order placed most recently with reduce.

Keep practising

Newsletter

New writing, when it lands.

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