Skip to content
Devtoolry

Basics · beginner

JavaScript Program to Find the Largest of Three Numbers

Find the largest of three numbers in JavaScript with if/else if/else and the && operator, then in one line with Math.max() and the spread operator.

Comparing three values is a classic exercise for if/else chains. Real code uses Math.max(), but writing the comparisons yourself shows how conditions are checked from top to bottom and how ties are handled.

The program

JavaScript
const a = 14, b = 27, c = 9;
let largest;

if (a >= b && a >= c) {
  largest = a;
} else if (b >= a && b >= c) {
  largest = b;
} else {
  largest = c;
}

console.log("The largest number is", largest);
Output
The largest number is 27

How it works

  1. The first condition checks that a is at least as big as both other numbers. 14 >= 27 is false, so && stops and the whole condition is false.
  2. The else if checks b the same way: both comparisons are true, so largest becomes 27.
  3. Once a branch runs, the rest of the chain is skipped.
  4. Using >= rather than > means ties still produce an answer: with 5, 5, 3 the first branch picks 5.

Watch it run line by line

Watch largest in the global frame: it is undefined until the else if branch assigns 27. Change c to 50 and visualize again to see the chain fall through to else.

“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: With Math.max()

Math.max() takes any number of arguments. For an array, spread it into the call with ...; for very large arrays (hundreds of thousands of items) use reduce() instead, because spreading has an argument limit.

JavaScript
console.log(Math.max(14, 27, 9));
const values = [3.5, -2, 8.25];
console.log(Math.max(...values));
console.log(Math.max());
Output
27
8.25
-Infinity

Common mistakes

  • Comparing strings from prompt(): "9" > "27" is true because strings are compared character by character. Convert with Number() first.
  • Writing if (a > b && c): the && c part only checks that c is not 0 (truthy), not that a > c.
  • Calling Math.max with an array (Math.max(values)) returns NaN. Spread it: Math.max(...values).

Try it yourself

  • Also print the smallest number without Math.min().
  • Sort the three numbers in ascending order with only if statements.

Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.