JavaScript Code


Largest of Three Numbers Program in JavaScript


Largest of Three Numbers Program

In this tutorial, you are given three numbers. Write a JavaScript program with a function that takes three numbers as arguments, finds the largest of these three numbers, and returns the largest number.

Solution

To find the largest of three numbers in JavaScript,

  1. Consider that num1, num2, and num3 are the three numbers
  2. If num1 is greater than both num2 and num3, then num1 is the largest,
  3. Else if num2 is greater than num3, then num2 is the largest,
  4. Else num3 is the largest

Program

1. In the following program, we find largest of three numbers using if-else-if statement.

function findLargest(num1, num2, num3) {
    if (num1 > num2 && num1 > num3) {
        return num1;
    } else if (num2 > num3) {
        return num2;
    } else {
        return num3;
    }
}

var num1 = 5;
var num2 = 8;
var num3 = 2;

const result = findLargest(num1, num2, num3);
console.log('Largest : ' + result);