Largest Among Three Numbers

Program to find the largest of three numbers

JavaScriptBeginner
JavaScript
// 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));

Output

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

This program demonstrates multiple approaches to find the largest number.

Method 1: If-Else Chain

Using logical AND (&&) operator:

javascript
if (a >= b && a >= c) {
    // a is largest
} else if (b >= a && b >= c) {
    // b is largest
} else {
    // c is largest
}

Logical Operators

  • &&: AND - both conditions must be true
  • ||: OR - at least one condition must be true
  • !: NOT - reverses boolean value

Method 2: Math.max()

Built-in JavaScript function:

javascript
Math.max(a, b, c);

Pros:

  • Simple and concise
  • Works with any number of arguments
  • Built-in, optimized

Method 3: Function Approach

Reusable function with clear logic:

javascript
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:

javascript
function findLargestArray(...numbers) {
    return Math.max(...numbers);
}

Spread Operator (...)

  • Expands array/arguments
  • Math.max(...[1, 2, 3])Math.max(1, 2, 3)
  • Very flexible for multiple values

When to Use:

  • Math.max(): Simplest, built-in

  • If-else: Learning logic, custom conditions

  • Function: Reusable code

  • Spread: Variable number of inputs