Sunday, September 22, 2024
Google search engine
HomeLanguagesJavascriptHow to find largest of three numbers using JavaScript ?

How to find largest of three numbers using JavaScript ?

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




<script>
    var x=5;
    var y=10;
    var z=15;
    if(x>y && x>z) console.log("X = "+x+" is the greatest");
    else if(z>x && z>y) console.log("Z = "+z+" is the greatest");
    else console.log("Y = "+y+" is the greatest");
</script>


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




<script>
    var x=5;
    var y=10;
    var z=15;
    console.log(Math.max(x,y,z)+" is the greatest");
</script>


Output:

15 is the greatest

RELATED ARTICLES

Most Popular

Recent Comments