find smallest number in array javascript using for loop

How to Find the Smallest Number in Array Using For Loop in JavaScript

As a web developer, I have come across situations where I needed to find the smallest number in an array. In JavaScript, there are several ways to achieve this, but one of the most straightforward methods is by using a for loop.

Step 1: Create an Array

First, we need to create an array of numbers. For this example, let's create an array of five numbers:


    const numbers = [10, 5, 8, 3, 6];
  

Step 2: Initialize a Variable

Next, we need to initialize a variable to hold the smallest number. We can set the initial value of this variable to the first element of the array:


    let smallestNumber = numbers[0];
  

Step 3: Use a For Loop

Now, we can use a for loop to iterate through the array and compare each element to the current value of the smallestNumber variable. If an element is smaller than the current smallest number, we update the smallestNumber variable:


    for (let i = 1; i < numbers.length; i++) {
      if (numbers[i] < smallestNumber) {
        smallestNumber = numbers[i];
      }
    }
  

In this for loop, we start at index 1 instead of index 0 because we already compared the first element to the smallestNumber variable in the initialization step.

Step 4: Output the Result

Finally, we can output the smallest number by logging it to the console:


    console.log("The smallest number is: " + smallestNumber);
  

Multiple Ways to Achieve the Same Result

There are several other ways to find the smallest number in an array using JavaScript. Here are a few examples:

  • Using the Math.min() function:

    const smallestNumber = Math.min(...numbers);
  
  • Using the reduce() method:

    const smallestNumber = numbers.reduce((acc, curr) => acc < curr ? acc : curr);
  

While these methods may be shorter and more concise, I find that using a for loop is easier to understand and more beginner-friendly.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe