What is Math min() Method in JavaScript

JavaScript Math min() is a built-in function that returns the smallest value among the numbers provided as arguments.

Syntax

Math.min(x, y, z, ...)

Parameter(s)

The numbers out of which the minimum is to be determined.

Return Value

The minimum of all the parameters passed.

See the following method.

JavaScript Math min()

Note

  1. If no argument is passed, this method returns positive infinity.
  2. If arguments cannot be converted into valid numbers, this method returns NaN.
  3. If the parameter is null, this method treats it as 0.
  4. If the parameter is an empty string, this method treats it as 0.
  5. If the parameter is an empty array, this method treats it as 0.
  6. If one argument is positive zero, and the other is negative zero, then the min() method returns negative zero as it considers negative zero to be strictly smaller than positive zero.

Example 1

console.log(Math.min(1, 2, 3));
console.log(Math.min(-1, 2, 3, -6));
console.log(Math.min(0, 0, -3));
console.log(Math.min(-1, -2));
console.log(Math.min(-5, -2, -3, 1));

Output

1
-6
-3
-2
-5

Example 2

console.log(Math.min());

Output

node app
Infinity

Example 3

The following code demonstrates the cases where NaN is returned and can be avoided.

var a = "JavaScript"; //non-numeric string
var b = [1, 2, 3, 4]; //array with more than one element
var c; //undefined variable
var d = {}; //empty object

console.log(Math.min(a, 1));
console.log(Math.min(b, 2));
console.log(Math.min(c, 3));
console.log(Math.min(d, 4));

var e = "23"; //numeric string
var f = [10]; //array with a single element

console.log(Math.min(e, 5));
console.log(Math.min(f, 1));

Output

NaN
NaN
NaN
NaN
5
1

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.