Minimums and Maximums

In both math and programming, the idea of minimum and maximum functions is important. When looking at two numbers \(a\) and \(b\), we say that the minimum (or "min" for short) of the two numbers is the number that is less than the other. On the other hand, the maximum (or "max") is the number that is greater than the other.

For example, when looking at 3 and 5, we would say that the min of these two numbers is 3, while the max is 5. In mathematical notation, we would write this as \[ \min(3,5) = 3 \quad\text{and}\quad \max(3,5) = 5 \] On this site we can use similar notation - we have a min() function and max() function that behave just like the math versions. The editor below shows this.

print( min(3,5) );
print( max(3,5) );

Try editing the numbers in the code above and see what happens.

Finding the minimum of two numbers is somewhat easy. In fact, we could have tested this using the < operator. However, it is often useful to find the minimum of a collection of numbers. To do this, we can do the following:

  1. Create a variable to hold the "current" minimum number. Let's call ours minNumber. We will set this equal to the first element of our list.
  2. We will now loop through our list of numbers. For each element in our list, if the number is smaller than our current minimum, minNumber, we will replace minNumber with this smaller number.
  3. Once we've looped through all of our numbers, minNumber should contain the smallest number.

The code below shows this in action. An array a of 10 random numbers between 0 and 100 is defined behind the scenes, and we will find the minimum of this array.

print(`a = ${a}`);

// set minNumber to the first element of a
var minNumber = a[0];

// Loop through a...
for (var i = 0; i < a.length; i++) {
	// Set minNumber to the smaller of minNumber and a[i]
	minNumber = min(minNumber, a[i]);

print(`Min number: ${minNumber}`);

Notice that in Line (9) we set minNumber = min(minNumber, a[i]). This tells the computer to find the smaller of minNumber and a[i], and use that for the new value of minNumber.


Activity: Max of a list of numbers

An array a of 10 random numbers between 0 and 100 is defined behind the scenes. Use a for loop to determine the maximum number of this array.

print(`a = ${a}`);


Activity: Defining the min function

We've been using a min() function that is defined for us behind the scenes. But, we can define our own minimum function! Define a function min2() that takes two numbers as its arguments, and then returns the smaller of the two numbers. We've added a little code for you.

function min2(a, b) {
	return 0;

print( min2(3, 5) );
print( min2(-7, -10) );