How to Use Math.max and Math.min in JavaScript
Use
Math.max() to find the largest number and Math.min() to find the smallest number from a list of values in JavaScript. Pass numbers as arguments or use the spread operator to handle arrays.Syntax
Math.max(value1, value2, ...) returns the largest number among the arguments.
Math.min(value1, value2, ...) returns the smallest number among the arguments.
You can pass numbers directly or use the spread operator ... to pass an array.
javascript
Math.max(3, 7, 2, 9) Math.min(3, 7, 2, 9) const numbers = [3, 7, 2, 9]; Math.max(...numbers) Math.min(...numbers)
Output
9
2
9
2
Example
This example shows how to find the highest and lowest numbers from a list using both direct arguments and an array with the spread operator.
javascript
const values = [10, 5, 20, 8]; const maxDirect = Math.max(10, 5, 20, 8); const minDirect = Math.min(10, 5, 20, 8); const maxFromArray = Math.max(...values); const minFromArray = Math.min(...values); console.log('Max using direct args:', maxDirect); console.log('Min using direct args:', minDirect); console.log('Max using array:', maxFromArray); console.log('Min using array:', minFromArray);
Output
Max using direct args: 20
Min using direct args: 5
Max using array: 20
Min using array: 5
Common Pitfalls
Passing an array directly to Math.max() or Math.min() without the spread operator returns NaN because these functions expect separate numbers, not an array.
Also, calling these functions without arguments returns -Infinity for Math.max() and Infinity for Math.min(), which can cause unexpected results.
javascript
const nums = [1, 2, 3]; // Wrong: passing array directly console.log(Math.max(nums)); // NaN // Right: using spread operator console.log(Math.max(...nums)); // 3 // No arguments console.log(Math.max()); // -Infinity console.log(Math.min()); // Infinity
Output
NaN
3
-Infinity
Infinity
Quick Reference
| Function | Purpose | Example Usage | Returns |
|---|---|---|---|
| Math.max() | Finds the largest number | Math.max(1, 5, 3) | 5 |
| Math.min() | Finds the smallest number | Math.min(1, 5, 3) | 1 |
| Spread operator | Pass array elements as separate arguments | Math.max(...[1, 5, 3]) | 5 |
Key Takeaways
Use Math.max() to get the largest number and Math.min() for the smallest number from arguments.
Use the spread operator (...) to pass an array to Math.max() or Math.min().
Passing an array directly without spreading causes NaN.
Calling Math.max() or Math.min() with no arguments returns -Infinity or Infinity respectively.
These functions only work with numbers passed as separate arguments, not arrays.