The syntax of the Math.min()
function is:
Math.min(n1, n2, ..., nx)
min()
, being a static method, is called using the Math
class name.
Math.min() Parameters
The Math.min()
function takes in arbitrary (one or more) numbers as arguments.
Return value from Math.min()
- Returns the smallest of the given numbers.
- Returns
NaN
if at least one argument cannot be converted to a number. - Returns
Infinity
if no arguments are given.Infinity
is the initial comparant as all numbers are smaller thanInfinity
.
Example 1: Using Math.min()
// using Math.min()
var num = Math.min(12, 4, 5, 9, 0, -3);
console.log(num); // -3
var num = Math.min(0.456, 1);
console.log(num); // 0.456
// Returns Infinity for no arguments
var num = Math.min();
console.log(num); // Infinity
// Returns NaN if any non-numeric argument
var num = Math.min("JS", 2, 5, 79);
console.log(num); // NaN
Output
-3 0.456 Infinity NaN
Example 2: Using Math.min() on Array
// Math.min() on arrays
// Using the spread operator
var numbers = [4, 1, 2, 55, 9];
var minNum = Math.min(...numbers);
console.log(minNum); // 1
// make custom function
function getMinInArray(arr) {
return Math.min(...arr);
}
numbers = ["19", 4.5, -7];
console.log(getMinInArray(numbers)); // -7
Output
1 -7
As you can see, we can use the new spread operator ...
to destructure the array in the function call and pass it to Math.min()
and obtain the smallest number.
Recommended readings: