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.
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.
15 is the greatest
Please Login to comment...