JavaScript Program to Find the Largest Among Three Numbers

To understand this example, you should have the knowledge of the following JavaScript programming topics:


You can find the largest among three numbers using the if...else statement.

Example 1: Largest Number Among Three Numbers

// program to find the largest among three numbers

// take input from the user
const num1 = parseFloat(prompt("Enter first number: "));
const num2 = parseFloat(prompt("Enter second number: "));
const num3 = parseFloat(prompt("Enter third number: "));
let largest;

// check the condition
if(num1 >= num2 && num1 >= num3) {
    largest = num1;
}
else if (num2 >= num1 && num2 >= num3) {
    largest = num2;
}
else {
    largest = num3;
}

// display the result
console.log("The largest number is " + largest);

Output

Enter first number: -7
Enter second number: -5
Enter third number: -1
The largest number is -1

In the above program, parseFloat() is used to convert numeric string to number. If the string is a floating number, parseFloat() converts the string into a floating point number.

The numbers are compared with one another using greater than or equal to >= operator. And the if...else if...else statement is used to check the condition.

Here, logical AND && is also used to check two conditions.


You can also use the JavaScript built-in Math.max() function to find the largest among the numbers.

Example2: Using Math.max()

// program to find the largest among three numbers

// take input from the user
const num1 = parseFloat(prompt("Enter first number: "));
const num2 = parseFloat(prompt("Enter second number: "));
const num3 = parseFloat(prompt("Enter third number: "));

const largest = Math.max(num1, num2, num3);

// display the result
console.log("The largest number is " + largest);

Output

Enter first number: 5
Enter second number: 5.5
Enter third number: 5.6
The largest number is 5.6

Math.max() returns the largest number among the provided numbers.


Also Read:

  • Math.min() - to find the smallest among the numbers

Before we wrap up, let’s put your knowledge of JavaScript Program to Find the Largest Among Three Numbers to the test! Can you solve the following challenge?

Challenge:

Write a function to find the largest of two numbers.

  • Return the larger number between num1 and num2.
  • For example, if num1 = 12 and num2 = 8, the expected output is 12.
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges