totn JavaScript

JavaScript: Math min() function

This JavaScript tutorial explains how to use the math function called min() with syntax and examples.

Description

In JavaScript, min() is a function that is used to return the smallest value from the numbers provided as parameters. Because the min() function is a static function of the Math object, it must be invoked through the placeholder object called Math.

Syntax

In JavaScript, the syntax for the min() function is:

Math.min([number1, number2, ... number_n]);

Parameters or Arguments

number1, number2, ... number_n
Optional. The numbers that will be evaluated to determine the smallest value.

Returns

The min() function returns the smallest value from the numbers provided.

If no parameters are provided, the min() function will return Infinity.

If any of the parameters provided are not numbers, the min() function will return NaN.

Note

  • Math is a placeholder object that contains mathematical functions and constants of which min() is one of these functions.

Example

Let's take a look at an example of how to use the min() function in JavaScript.

For example:

console.log(Math.min(5, 10));
console.log(Math.min(60, 40, 20));
console.log(Math.min(-3, -6, -9, -12));

In this example, we have invoked the min() function using the Math class.

We have written the output of the min() function to the web browser console log, for demonstration purposes, to show what the min() function returns.

The following will be output to the web browser console log:

5
20
-12

In this example, the first output to the console log returned 5 which is the smallest of the values 5 and 10.

The second output to the console log returned 20 which is the smallest of the values 60, 40 and 20.

The third output to the console log returned -12 which is the smallest of the values -3, -6, -9 and -12.

Using the min() function to find the Largest Value in an Array

Finally, we'll take a look at how to use the min() function to find the smallest value in an array.

For example:

var totn_array = [2, 4, 6, 8, 10];

console.log(Math.min(...totn_array));

The following will be output to the web browser console log:

2

In this example, the min() method returned 2 which is the smallest value from the array called totn_array. This array consisted of 5 elements with the numeric values: 2, 4, 6, 8 and 10.