Largest Among Three Numbers in JavaScript

Math.max exists. The if version is so you see the ties.

BeginnerConditional ProgramsExample 2 of 5
largest-among-three-numbers.js
1// Method 1: Using if-else
2let a = 10, b = 25, c = 15;
3let largest;
4
5if (a >= b && a >= c) {
6 largest = a;
7} else if (b >= a && b >= c) {
8 largest = b;
9} else {
10 largest = c;
11}
12
13console.log("Largest among", a + ",", b + ",", c, "is:", largest);
14
15// Method 2: Using Math.max()
16let num1 = 10, num2 = 25, num3 = 15;
17let max = Math.max(num1, num2, num3);
18console.log("Largest using Math.max():", max);
19
20// Method 3: Using function
21function findLargest(x, y, z) {
22 if (x >= y && x >= z) {
23 return x;
24 } else if (y >= x && y >= z) {
25 return y;
26 } else {
27 return z;
28 }
29}
30
31console.log("Largest:", findLargest(5, 8, 3));
32
33// Method 4: Using array and spread operator
34function findLargestArray(...numbers) {
35 return Math.max(...numbers);
36}
37
38console.log("Largest from array:", findLargestArray(10, 25, 15, 30, 5));

Output

Largest among 10 , 25 , 15 is: 25
Largest using Math.max(): 25
Largest: 8
Largest from array: 30

What's going on

>= not > when ties are allowed. Two equal maxima with > pick the wrong one.

Math.max(a, b, c) is shorter. Write the comparisons once so they live in your head.