Skip to content
the poor coder

find smallest number in array javascript using for loop

Poor Man
Published
Reading time
2 min read
On this page

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:

Text

    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:

Text

    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:

Text

    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:

Text

    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:
Text

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

    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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC