How to useArray.sort() in Javascript

Put the numbers in an array and use Array.sort() to sort them in ascending order. The largest number will be at the end of the array.

Example: In this example, we are using Array.sort().

Javascript




function findLargest(num1, num2, num3) {
  const numbers = [num1, num2, num3];
  numbers.sort((a, b) => a - b);
  return numbers[numbers.length - 1];
}
 
// Example usage:
const largestNumber = findLargest(10, 5, 8);
console.log("Largest number:", largestNumber);


Output

Largest number: 10


How to find largest of three numbers using JavaScript ?

To find the largest of three numbers using JavaScript, we have multiple approaches. In this article, we are going to learn how to find the largest of three numbers using JavaScript.

Below are the approaches to finding the largest of three numbers using JavaScript:

Table of Content

  • Using Conditional Statements (if-else)
  • Using the Math.max() Method
  • Using the Spread Operator with Math.max()
  • Using the Ternary Operator
  • Using Array.sort()

Similar Reads

Approach 1: Using Conditional Statements (if-else)

This is a straightforward approach using if-else statements to compare the numbers and find the largest one....

Approach 2: Using the Math.max() Method

...

Approach 3: Using the Spread Operator with Math.max()

The Math.max() method can be used to find the maximum of a list of numbers....

Approach 4: Using the Ternary Operator

...

Approach 5: Using Array.sort()

Spread the numbers in an array using the spread operator and then use Math.max()....

Contact Us