Explain Codes LogoExplain Codes Logo

How might I find the largest number contained in a JavaScript array?

javascript
array-methods
performance
best-practices
Nikita BarsukovbyNikita Barsukov·Feb 14, 2025
TLDR

To find the largest number in a JavaScript array swiftly, Math.max combined with the spread operator ... becomes your weapon of choice:

const max = Math.max(...[1, 2, 3, 90, 10, -20]); // returns 90

This nifty trick uses Math.max to compare and extract the maximum from the array arguments.

Ammunition for larger battles

Now, if you're dealing with a behemoth of an array, the spread operator will wave the white flag and return a "Maximum call stack size exceeded" error. Don't fret! A good ol' for loop comes to the rescue here:

let bigArray = [/* ... gazillions of numbers ... */]; let max = -Infinity; // Because nothing's lower than the infinite lows 🎵 for (let i = 0; i < bigArray.length; i++) { if (bigArray[i] > max) { max = bigArray[i]; // Eat, sleep, beat the max, repeat! 🔄 } }

This way, we set max to -Infinity before the loop starts, ensuring every number in the array has a chance to be the new max.

The beauty of reduce

You can also elegantly crunch arrays using the Array.reduce() method, it's less of a Hulk, more of a Doctor Strange:

const max = array.reduce((max, currentValue) => Math.max(max, currentValue), -Infinity);

This reduce spell makes the array elements follow each other while keeping track of the highest one seen so far, all in one pass.

What lies beneath: edge cases and performance

Your code should be as robust as an old Nokia 📱. It means it should work with empty arrays and non-numeric values:

const maxSafe = (array) => array.length ? Math.max(...array.filter(Number.isFinite)) : undefined;

This technique filters out non-finite numbers before hunting down the maximum. No room for false positives here!

And as with any great skill, the more you practice, the better you get. If efficiency is your goal for large datasets, benchmark tests can be your coach to select the best approach for the win. In most competitions, the custom for loop often outpaces others.

Array Mutations: Beware!

Using Array.sort() for finding the largest number feels like using a chainsaw for a scalpel:

let max = array.sort((a, b) => b - a)[0]; // The road less sorted 👀

This will chew your original array up and spit out a new sorted one, which might make your future endeavours with the array tricky.

The best tool for the job: comparing methods

Here's a tl;dr table 🍽️ to keep your thoughts ordered:

| Method        | Pros                | Cons                     | Edge Cases     |
|---------------|---------------------|--------------------------|----------------|
| Spread        | Speedy, Readable    | Stack size limitations   | Avoid emptiness|
| For loop      | Battle-tested, Robust | Not the prettiest kid | Start with -Infinity |
| Reduce        | Sophisticated, Reliable | Speed champ, only for small leagues | Failsafe for empty arrays|
| Sort          | Simplistic          | Mutates array, Efficiency for big leagues | Laughs in the face of non-number data |