Math.max()

ES1+

Returns the largest of the zero or more numbers given as input parameters.

Syntax

Math.max(value1, value2, ...)

Parameters

values number

Zero or more numbers

Return Value

number

The largest of the given numbers, or -Infinity if no arguments

Examples

JavaScript
console.log(Math.max(1, 3, 2));
console.log(Math.max(-1, -3, -2));
console.log(Math.max(...[4, 5, 6]));
Output:
// 3 -1 6

📌 When to Use

Use Math.max() for finding peak values, setting upper bounds, or comparing multiple numeric values simultaneously.

⚠️ Common Mistakes

Passing an array directly instead of spreading it: Math.max([1,2,3]) returns NaN, use Math.max(...arr).

Stack overflow when spreading very large arrays (100,000+ elements). Use reduce instead.

✅ Best Practices

For large arrays, use array.reduce((a, b) => Math.max(a, b)) to avoid call stack limits.

Use Math.max() with default values: Math.max(userInput, 0) ensures non-negative results.

⚡ Performance Notes

Math.max() with spread operator creates a new arguments list. For arrays over 100k elements, reduce() is more memory-efficient and avoids stack overflow.

🌍 Real World Example

Responsive Image Size Calculator

Calculate optimal image dimensions while respecting minimum and maximum constraints.

function calculateImageSize(originalWidth, containerWidth, options = {}) {
  const { minWidth = 100, maxWidth = 1200 } = options;

  // Ensure width is within bounds
  const constrainedWidth = Math.max(
    minWidth,
    Math.min(maxWidth, containerWidth)
  );

  const scale = constrainedWidth / originalWidth;
  return {
    width: constrainedWidth,
    scale: Math.max(0.1, Math.min(scale, 2)) // Scale between 0.1x and 2x
  };
}

console.log(calculateImageSize(800, 600)); // { width: 600, scale: 0.75 }
console.log(calculateImageSize(800, 50, { minWidth: 200 })); // { width: 200, scale: 0.25 }

Related Methods