Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

Exercise: Finding The Minimum

Exercise 8 Very easy

Prerequisites for the exercise

  1. JavaScript Numbers Basics
  2. All previous chapters

Objective

Given an array of numbers, find the minimum.

Description

In a list of numbers, the smallest number is often referred to as the minimum.

In this exercise, you have to create a function min() to find and return the minimum element of a given array of numbers.

Here's the signature of the function:

function min(arr) {
   // Your code here.
}

arr is the array whose minimum we ought to find.

If the given array is empty, return the special number Infinity; otherwise return the minimum value.

Hints

Hint 1

Iterate over the given array, and at each iteration keep track of the minimum seen thus far.

Hint 2

In the beginning, assume Infinity as the minimum.

View Solution

New file

Inside the directory you created for this course on JavaScript, create a new folder called Exercise-8-Finding-The-Minimum and put the .html solution files for this exercise within it.

Solution

It's impossible to find the minimum value of an arbitrary array without iterating over all the elements therein.

Likewise, the first and foremost thing we'll do is to set up a for loop iterating over arr:

function min(arr) {
   for (var i = 0; i < arr.length; i++) {
      // Code to go here.
   }
}

The next thing is to check each element inside the loop with the previously-known minimum. If it's smaller than the previously-known minimum, then obviously we need to change that value and point it to the current element.

To start with, however, we don't have any previously-known minimum. But we can use one — the special number Infinity. Every number is less than Infinity, hence it could be a good candidate for the previously-known minimum before the loop begins.

Here's the complete code:

function min(arr) {
   var minValue = Infinity;

   for (var i = 0; i < arr.length; i++) {
      if (arr[i] < minValue) {
         minValue = arr[i];
      }
   }

   return minValue;
}

The variable minValue serves to keep track of the minimum seen thus far in the array. In the end, it's returned. If the given array is empty, the loop's body doesn't execute as its condition doesn't get fulfilled, and likewise Infinity is returned, just as desired.

Let's try running this on a couple of arrays:

min([-5, 1, 0, 5, 6])
-5
min([0, 0, 0])
0
min([1, 9, 10, 100])
1
min([])
Infinity

Perfect.