JavaScript Program to Find Largest of Two Numbers
Use the JavaScript code
const largest = (a, b) => (a > b ? a : b); to find the largest of two numbers by comparing them with the > operator.Examples
Input5, 10
Output10
Input-3, -7
Output-3
Input8, 8
Output8
How to Think About It
To find the largest of two numbers, compare them using the greater than operator
>. If the first number is greater, it is the largest; otherwise, the second number is the largest. If both are equal, either can be returned.Algorithm
1
Get the two numbers as input.2
Compare the first number with the second using the > operator.3
If the first number is greater, select it as the largest.4
Otherwise, select the second number as the largest.5
Return the selected largest number.Code
javascript
function findLargest(a, b) { if (a > b) { return a; } else { return b; } } console.log(findLargest(5, 10)); console.log(findLargest(-3, -7)); console.log(findLargest(8, 8));
Output
10
-3
8
Dry Run
Let's trace the input (5, 10) through the code
1
Compare numbers
Check if 5 > 10, which is false
2
Select largest
Since 5 > 10 is false, select 10 as largest
3
Return result
Return 10
| a | b | a > b | largest |
|---|---|---|---|
| 5 | 10 | false | 10 |
Why This Works
Step 1: Compare two numbers
The code uses the > operator to check which number is bigger.
Step 2: Choose the larger number
If the first number is greater, it returns that; otherwise, it returns the second.
Step 3: Return the largest
The function returns the largest number as the final result.
Alternative Approaches
Using Math.max()
javascript
function findLargest(a, b) { return Math.max(a, b); } console.log(findLargest(5, 10));
This is simpler and uses built-in function but may be less clear for beginners.
Using ternary operator
javascript
const findLargest = (a, b) => (a > b ? a : b); console.log(findLargest(5, 10));
This is concise and modern JavaScript style using arrow functions.
Complexity: O(1) time, O(1) space
Time Complexity
The program compares two numbers once, so it runs in constant time O(1).
Space Complexity
It uses a fixed amount of memory regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
All approaches run in constant time; using Math.max is simplest and most readable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| If-else comparison | O(1) | O(1) | Clear logic for beginners |
| Math.max() | O(1) | O(1) | Concise and built-in function |
| Ternary operator | O(1) | O(1) | Short and modern syntax |
Use
Math.max(a, b) for a quick and readable way to find the largest number.Beginners often use
= instead of == or > for comparison, causing wrong results.