Largest Among Three Numbers
Program to find the largest of three numbers
JavaScript Largest Among Three Numbers Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Method 1: Using if-else
let a = 10, b = 25, c = 15;
let largest;
if (a >= b && a >= c) {
largest = a;
} else if (b >= a && b >= c) {
largest = b;
} else {
largest = c;
}
console.log("Largest among", a + ",", b + ",", c, "is:", largest);
// Method 2: Using Math.max()
let num1 = 10, num2 = 25, num3 = 15;
let max = Math.max(num1, num2, num3);
console.log("Largest using Math.max():", max);
// Method 3: Using function
function findLargest(x, y, z) {
if (x >= y && x >= z) {
return x;
} else if (y >= x && y >= z) {
return y;
} else {
return z;
}
}
console.log("Largest:", findLargest(5, 8, 3));
// Method 4: Using array and spread operator
function findLargestArray(...numbers) {
return Math.max(...numbers);
}
console.log("Largest from array:", findLargestArray(10, 25, 15, 30, 5));Largest among 10 , 25 , 15 is: 25 Largest using Math.max(): 25 Largest: 8 Largest from array: 30
Understanding Largest Among Three Numbers
This program demonstrates multiple approaches to find the largest number.
Method 1: If-Else Chain
Using logical AND (&&) operator:
if (a >= b && a >= c) {
} else if (b >= a && b >= c) {
// b is largest
} else {
// c is largest
}
// a is largestLogical Operators
&&: AND - both conditions must be true||: OR - at least one condition must be true!: NOT - reverses boolean valueMethod 2: Math.max()
Built-in JavaScript function:
Math.max(a, b, c);
Pros:
Method 3: Function Approach
Reusable function with clear logic:
function findLargest(x, y, z) {
if (x >= y && x >= z) return x;
if (y >= x && y >= z) return y;
}
return z;Method 4: Spread Operator (ES6)
Using rest parameters:
function findLargestArray(...numbers) {
}
return Math.max(...numbers);Spread Operator (`...`)
Math.max(...[1, 2, 3]) → Math.max(1, 2, 3)When to Use:
-
Math.max()
: Simplest, built-in
-
If-else
: Learning logic, custom conditions
-
Function
: Reusable code
-
Spread
: Variable number of inputs
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.