Examples
- JavaScript Program to Check if a Number is Positive, Negative, or Zero
- JavaScript Program to Find the Largest Among Three Numbers
- JavaScript Program to Check Prime Number (4 Ways)
- JavaScript Program to Find the Factorial of a Number
- Armstrong Number in JavaScript (6 Programs)
- JavaScript Program to Find HCF or GCD
- JavaScript Program to Find LCM (5 Ways)
- JavaScript Program to Convert Decimal to Binary
JavaScript Program to Find the Largest Among Three Numbers
Finding the largest among three numbers is a common exercise for beginners in JavaScript programming. This tutorial will demonstrate how to accept three inputs, compare them using different methods, and determine the largest value.
By understanding these methods, you’ll gain deeper insights into logical operations, conditional statements, and JavaScript’s built-in functions. Mastering this concept is a stepping stone to solving more complex programming challenges.
Find Largest Among Three Numbers in JavaScript Using if-else Statements
The if-else conditional statement provides a straightforward approach to finding the largest among three numbers.
Code
function findLargest(a, b, c) {
if (a >= b && a >= c) {
console.log(`${a} is the largest number`);
} else if (b >= a && b >= c) {
console.log(`${b} is the largest number`);
} else {
console.log(`${c} is the largest number`);
}
}
// Example Usage
findLargest(10, 20, 15);
findLargest(25, 20, 30);
Output
20 is the largest number
30 is the largest number
Explanation
-
Compare a with b and c to see if it’s the largest.
-
If not, check if b is greater than or equal to the others.
-
If neither is true, c is the largest.
JavaScript Program to Find the Largest Among Three Numbers Using Ternary Operators
Ternary operators can simplify the logic to find the largest number.
Code
function findLargest(a, b, c) {
let largest = (a >= b && a >= c) ? a : (b >= a && b >= c) ? b : c;
console.log(`${largest} is the largest number`);
}
// Example Usage
findLargest(5, 12, 7);
findLargest(9, 3, 9);
Output
12 is the largest number
9 is the largest number
Explanation
-
The first condition checks if a is the largest.
-
If false, the second condition evaluates if b is the largest.
-
Otherwise, c is assigned as the largest.
JavaScript Program to Find the largest of 3 Number Using Math Function
JavaScript’s Math.max function provides a concise way to find the largest number.
Code
function findLargest(a, b, c) {
let largest = Math.max(a, b, c);
console.log(`${largest} is the largest number`);
}
// Example Usage
findLargest(8, 14, 3);
findLargest(22, 11, 15);
Output
14 is the largest number
22 is the largest number
Explanation
-
Math.max takes any number of arguments and returns the largest value.
-
It eliminates the need for explicit comparisons, making the code more concise.