Select Page

How to find largest of three numbers using JavaScript ?

Gaurav
Published: November 28, 2022

In this article, we will find the largest of 3 given numbers using JavaScript.

We will do so by making use of the simple if-else statements in JavaScript. JavaScript is a front-end language that can print directly to the console as well as to the view page like .html.

Let us look at the console log outputs and the corresponding code.

Approach 1: Using the if-else statements

The if-else statements used for checking conditions will be used to compare the 3 numbers. The variables will be called x, y and z. We compare x with y and z, y with x and z, and z with x and y to see which is the largest number.

Example: In the example below it is first checked if x(=5) is greater than y(=10) and z (=15) which is false. Then the program checks if z(15) is greater than x(=5) and y (=10) which returns true and hence 15 is the largest.

Javascript

 ``

Output:

`Z = 15 is the greatest`

There are multiple approaches to finding the largest of 3 numbers, let us have a look at the other approaches as well:

Method 2: Using the Math.max function

The Math.max() function returns the largest of the numbers given as input parameters, or -Infinity if there are no parameters. Our variables named x,y, and z are simply passed to Math.max() and we get the highest of the 3 numbers. This function can take multiple arguments and not just 3.

Example:

Javascript

 ``

Output:

`15 is the greatest`

Source: www.geeksforgeeks.org