Open In App

JavaScript Program to Find the Smallest Among Three Numbers

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, finding the smallest among three numbers is a common task in programming. There are multiple approaches to achieving this, each with its advantages and use cases.

There are several approaches in JavaScript to find the smallest among three numbers which are as follows:

Using Conditional Statements

The simplest approach is to use conditional statements (if, else if, else) to compare the numbers and find the smallest one.

Example: To demonstrate comparing the given numbers pairwise to determine the smallest among them by returning that smallest number.

Javascript




function findSmallest(num1, num2, num3) {
    if (num1 <= num2 && num1 <= num3) {
        return num1;
    } else if (num2 <= num1 && num2 <= num3) {
        return num2;
    } else {
        return num3;
    }
}
 
// Example usage
const num1 = 10;
const num2 = 5;
const num3 = 12;
 
const smallest = findSmallest(num1, num2, num3);
console.log("The smallest number is:", smallest);


Output

The smallest number is: 5

Using Math.min() Function

You can utilize the `Math.min()` function, which directly returns the smallest among the provided numbers, making it a concise and efficient approach to find the smallest among three numbers in JavaScript.

Example: To demonstrate using the Math.min() to find the minimum value among the three numbers num1, num2, and num3, returning the smallest number.

Javascript




function findSmallest(num1, num2, num3) {
    return Math.min(num1, num2, num3);
}
 
// Example usage
const num1 = 10;
const num2 = 5;
const num3 = 12;
 
const smallest = findSmallest(num1, num2, num3);
console.log("The smallest number is:", smallest);


Output

The smallest number is: 5

Using sort method

Sorting the numbers in ascending order using sort() method and then selecting the first element (smallest) can also determine the smallest among three numbers.

Example: It creates an array containing the three input numbers, sorts them using a comparison function that orders them numerically, and then returns the first element of the sorted array, which is the smallest number among them.

Javascript




function findSmallest3(num1, num2, num3) {
    let sortedArray = [num1, num2, num3]
        .sort((a, b) => a - b);
    return sortedArray[0];
}
// Example usage
const num1 = 10;
const num2 = 5;
const num3 = 12;
 
const smallest = findSmallest3(num1, num2, num3);
console.log("The smallest number is:", smallest);


Output

The smallest number is: 5


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads