JavaScript Reference ยท Math
Math.min()
Reference for Math.min(): finding the smallest of several numbers, using it with arrays and spread, clamping values, and handling NaN and empty input.
Math.min() takes any number of arguments and returns the smallest one. Every argument is converted to a number first, so Math.min("3", 5) is 3. If any argument cannot be converted to a number, the result is NaN.
It is a static function of the Math object. You never create a Math instance, and the method does not look at arrays by itself: to find the smallest item of an array, spread the array into the call.
Math.min(value1, value2, /* โฆ, */ valueN)
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Math.min() Math.min(value1) Math.min(value1, value2) Math.min(value1, value2, /* โฆ, */ valueN)
| Name | Description |
|---|---|
value1, โฆ, valueN |
The numbers to compare. Each is converted with the same rules as Number(). |
Return value: the smallest argument as a number. With no arguments the result is Infinity. If any argument converts to NaN, the result is NaN.
Exceptions: none for ordinary values. A BigInt argument throws a TypeError, because it cannot be converted to a number implicitly.
Usage notes
- Empty input gives
Infinity. That is the identity for "smallest of nothing", soMath.min(...[])isInfinity, not an error. Guard for empty arrays when the answer matters. - One
NaNpoisons the result.Math.min(3, NaN, 1)isNaN. Filter out bad values first, for example withNumber.isFinite. - Type coercion surprises.
nullbecomes0,truebecomes1, an empty array becomes0, andundefinedbecomesNaN. Convert and validate data before comparing. - Negative zero is considered smaller than positive zero:
Math.min(0, -0)is-0. - Very large arrays. Spreading millions of items into a call can exceed the engine's argument limit and throw a
RangeError. For huge arrays usearray.reduce((a, b) => (b < a ? b : a))or a plain loop. - Strings are not compared alphabetically.
Math.min("apple", "pear")isNaN. Use a comparison operator orlocaleCompare()for text. - To find the position of the smallest item, use
array.indexOf(Math.min(...array))or a loop that remembers the index.
Browser support
Supported in every browser and in Node.js since the first versions of JavaScript.
Related
Math.max()Math.abs()Array.prototype.reduce()- Lesson: The Math object
- Lesson: Spread and rest