Emmanuel Akinfulubi

JavaScriptBasic

Find the largest of three numbers in JavaScript

Beginner · 3 min read

Highest score, most expensive item, warmest day of the week: finding the largest value is one of the most common things code does with numbers. JavaScript has a built-in for it, Math.max. In this tutorial you will use it for three numbers, then for a list of any length, and you will meet two edge cases that catch people out.

You will write largestOfThree(a, b, c) and then largest(values), which takes an array. You need to know what a function and an array are. The spread syntax and reduce are explained below.

Math.max

Math.max takes any number of numbers and returns the biggest.

JavaScript

console.log(Math.max(3, 9, 5));  // 9
console.log(Math.max(-3, -9));   // -3

With negative numbers, the largest is the one closest to zero.

Spreading an array

Math.max wants separate numbers, not an array. If you pass an array, it can't read it:

JavaScript

console.log(Math.max([3, 9, 5])); // NaN

The spread syntax, three dots before the array, unpacks it into separate arguments. Math.max(...[3, 9, 5]) is the same as Math.max(3, 9, 5).

Here is the exercise. Try it on your own first if you like, or follow the steps below.

18 Largest of three numbers

easy

Return the largest of three numbers. Then show the version that works for any count.

Stuck? Three hints, smallest first
  1. 1. Math.max(a, b, c) does it directly.
  2. 2. For an array, spread it: Math.max(...values).
  3. 3. Math.max() with no arguments returns -Infinity, which is correct but rarely what a caller wants.

Step 1: three numbers

An arrow function is enough here: input on the left, value on the right.

Step 1

const largestOfThree = (a, b, c) => Math.max(a, b, c);
console.log(largestOfThree(3, 9, 5));    // 9
console.log(largestOfThree(9, 3, 5));    // 9
console.log(largestOfThree(-3, -9, -5)); // -3

Testing with the largest in different positions shows the order doesn't matter.

Step 2: any number of values

Spread the array into Math.max:

Step 2

function largest(values) {
  return Math.max(...values);
}
console.log(largest([3, 9, 5, 22, 7])); // 22
console.log(largest([42]));             // 42

Step 3: the empty list

Now try an empty array:

JavaScript

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

With nothing to compare, Math.max returns -Infinity. That is mathematically correct: it is the starting point that any real number beats. But in an app it is almost always a mistake. A "highest score" of -Infinity on an empty leaderboard is a bug nobody asked for, and it quietly carries on into any sums you do with it.

So refuse an empty list with a clear error:

Step 3

function largest(values) {
  if (values.length === 0) throw new RangeError('largest needs at least one value');
  return Math.max(...values);
}

Now the problem shows up at the moment it happens, with a message that says what went wrong.

Step 4: very large arrays

Spreading turns every item into a separate argument. JavaScript engines limit how many arguments a function call can take. For a list of a few thousand numbers you will never notice, but with hundreds of thousands, spreading can fail with a RangeError.

reduce avoids that. It walks the array once, keeping the best value so far:

Step 4

const best = [5, 1, 9, 3].reduce((best, n) => (n > best ? n : best), -Infinity);
console.log(best); // 9

For each number n, if it is bigger than best, it becomes the new best. The starting value -Infinity means the first real number always wins. The ? : is the ternary operator: condition ? ifTrue : ifFalse.

The full solution

The complete answer has both functions, shows Math.max() with no arguments, and finds the largest with reduce too. Press Run to see the output.

The answer

const largestOfThree = (a, b, c) => Math.max(a, b, c);

// For any number of values, spread the array in.
function largest(values) {
  if (values.length === 0) throw new RangeError('largest needs at least one value');
  return Math.max(...values);
}

console.log(largestOfThree(3, 9, 5));
console.log(largest([3, 9, 5, 22, 7]));

// The edge nobody expects:
console.log('Math.max() with nothing:', Math.max());

// And the limit of spreading: a very large array can exceed the argument limit,
// so reduce is the safe choice for those.
const bigSafe = [5, 1, 9, 3].reduce((best, n) => (n > best ? n : best), -Infinity);
console.log('via reduce:', bigSafe);

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('three numbers', largestOfThree(3, 9, 5), 9);
test('the largest is first', largestOfThree(9, 3, 5), 9);
test('negatives', largestOfThree(-3, -9, -5), -3);
test('any length', largest([3, 9, 5, 22, 7]), 22);
test('a single value', largest([42]), 42);
test('empty is refused', (() => { try { largest([]); return false; } catch { return true; } })(), true);
test('Math.max with no arguments is -Infinity', Math.max(), -Infinity);
test('reduce agrees', bigSafe, 9);

Math.max() returning -Infinity for no arguments is mathematically right — it is the identity for maximum — and is almost always a bug in practice, because it means an empty array silently produces a number instead of an error. Hence the explicit guard. The reduce version also matters for genuinely large arrays, where spreading hundreds of thousands of arguments can exceed the engine's limit.

Common mistakes

  • Passing an array straight to Math.max. Math.max([3, 9]) is NaN. Spread it: Math.max(...values).
  • Not handling an empty array. You get -Infinity instead of an error, and the bug shows up later somewhere else.
  • Starting reduce at 0. If every number is negative, 0 "wins" even though it isn't in the list. Start at -Infinity or at the first item.

Try it yourself

  1. Write smallest(values) with the same empty-list check, using Math.min.
  2. Write largestBy(items, key) that returns the object with the largest value for a property, like the most expensive product in a list.
  3. Return both the largest value and its position in the array: { value: 22, index: 3 }.

Keep practising

Newsletter

New writing, when it lands.

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