JavaScript: Find the Smallest Among Three Numbers

1. Introduction

Determining the smallest value among a set of numbers is a commonly encountered task in programming. It's a foundational comparison operation, much like finding the largest number. This capability is particularly important in areas like data analysis, algorithm optimization, and various problem-solving scenarios. In this article, we will walk through a straightforward JavaScript program to find the smallest number among three given numbers.

2. Program Overview

During this tutorial, we'll:

1. Initialize three distinct numbers.

2. Use conditional statements to make comparisons among these numbers.

3. Find and display the smallest number.

3. Code Program

let num1 = 12;    // First number
let num2 = 7;     // Second number
let num3 = 18;    // Third number

let smallest;     // Variable to store the smallest number

// Employing conditional statements to compare the numbers and find the smallest
if (num1 < num2 && num1 < num3) {
    smallest = num1;
} else if (num2 < num1 && num2 < num3) {
    smallest = num2;
} else {
    smallest = num3;
}

console.log("Among " + num1 + ", " + num2 + ", and " + num3 + ", the smallest number is: " + smallest + ".");

Output:

Among 12, 7, and 18, the smallest number is: 7.

4. Step By Step Explanation

1. Variable Declaration: We kick things off by defining three variables (num1, num2, and num3) with specific values. Additionally, the smallest variable is introduced, which will later hold the smallest number after our comparisons.

2. Comparison Through Conditional Statements: A series of if-else statements come into play to compare the numbers. These conditions verify each number against the other two, discerning the smallest of the three.

3. Assigning the Result: Once the smallest number is identified, it gets assigned to the smallest variable.

4. Result Presentation: The console.log function outputs the smallest number, delivering the information in a comprehensive and reader-friendly format.

Comments