0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Find Largest of Three Numbers

Use the code Math.max(num1, num2, num3) or compare numbers with if statements to find the largest of three numbers in JavaScript.
📋

Examples

Inputnum1=5, num2=10, num3=3
Output10
Inputnum1=7, num2=7, num3=7
Output7
Inputnum1=-1, num2=-5, num3=-3
Output-1
🧠

How to Think About It

To find the largest of three numbers, compare them two at a time using if statements or use the built-in Math.max function which returns the biggest number among the inputs.
📐

Algorithm

1
Get the three numbers as input.
2
Compare the first number with the second and third to find the largest.
3
Return or print the largest number.
💻

Code

javascript
const num1 = 5;
const num2 = 10;
const num3 = 3;

const largest = Math.max(num1, num2, num3);
console.log('Largest number is:', largest);
Output
Largest number is: 10
🔍

Dry Run

Let's trace the example with num1=5, num2=10, num3=3 through the code

1

Assign values

num1 = 5, num2 = 10, num3 = 3

2

Call Math.max

Math.max(5, 10, 3) returns 10

3

Print result

Output: 'Largest number is: 10'

StepOperationResult
1Assign num1=5, num2=10, num3=3Values set
2Calculate Math.max(5,10,3)10
3Print largest numberLargest number is: 10
💡

Why This Works

Step 1: Using Math.max

The Math.max function takes any number of arguments and returns the largest one, making it simple to find the biggest of three numbers.

Step 2: Comparing numbers manually

Alternatively, you can use if statements to compare numbers two at a time and keep track of the largest.

🔄

Alternative Approaches

Using if-else statements
javascript
const num1 = 5;
const num2 = 10;
const num3 = 3;

let largest = num1;
if (num2 > largest) {
  largest = num2;
}
if (num3 > largest) {
  largest = num3;
}
console.log('Largest number is:', largest);
This method is more manual but helps understand comparisons step-by-step.
Using ternary operators
javascript
const num1 = 5;
const num2 = 10;
const num3 = 3;

const largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
console.log('Largest number is:', largest);
This is a concise way using nested ternary operators but can be harder to read.

Complexity: O(1) time, O(1) space

Time Complexity

The program does a fixed number of comparisons or calls a built-in function that runs in constant time, so it is O(1).

Space Complexity

Only a few variables are used to store numbers and the result, so space complexity is O(1).

Which Approach is Fastest?

Using Math.max is fastest and simplest; manual comparisons are equally fast but more verbose.

ApproachTimeSpaceBest For
Math.maxO(1)O(1)Simplicity and readability
If-else statementsO(1)O(1)Learning comparisons step-by-step
Ternary operatorsO(1)O(1)Concise code but less readable
💡
Use Math.max for a clean and simple solution to find the largest number.
⚠️
Beginners often forget to compare all three numbers or only compare two, missing the largest.