Sub topic 12
Finding Extremes and Magnitudes: min, max, abs, and sign
This chapter covers four small Math functions that you will reach for constantly: Math.max, Math.min, Math.abs, and Math.sign. They look trivial, but each one converts its arguments, reacts to NaN, and has rules for -0 and empty input that can catch you out.
It assumes you have read the earlier chapters on NaN, Infinity, and -0, on converting values to numbers, and on the Math object. You should be comfortable with spread syntax (...) and Array.prototype.reduce.
The working model
All four functions follow the same pattern:
- Convert each argument to a number using the same rules as
Number(). - If any converted value is
NaN, returnNaN. - Otherwise compute the result, treating
-0as smaller than+0where it matters.
Once you know that they all convert their input first and that NaN always wins, most of their surprising results make sense.
Math.max and Math.min
Separate arguments, not arrays
Math.max and Math.min accept any number of separate arguments. They do not accept an array. To use them on an array, spread it into separate arguments.
const scores = [72, 95, 88, 61];
console.log(Math.max(72, 95, 88, 61)); // 95
console.log(Math.max(...scores)); // 95
console.log(Math.min(...scores)); // 61
// Passing the array itself converts it to a string first
console.log(Math.max(scores)); // NaN ("72,95,88,61" is not numeric)
console.log(Math.max([5])); // 5 ("5" is numeric, a misleading success)The last line is the dangerous case. A one-element array passes silently, so a bug that forgot the spread can survive tests that only use one item.
Empty input returns an infinity
With no arguments, Math.max() returns -Infinity and Math.min() returns Infinity. These are the identity values for each operation: every real number is larger than -Infinity, so it makes a correct starting point for a running maximum.
console.log(Math.max()); // -Infinity
console.log(Math.min()); // Infinity
console.log(Math.max(...[])); // -Infinity
function highestScore(list) {
if (list.length === 0) return null; // make "no data" explicit
return Math.max(...list);
}
console.log(highestScore([])); // null
console.log(highestScore([3, 9, 4])); // 9NaN poisons the result
If any argument converts to NaN, the result is NaN, wherever it appears in the list. This differs from a hand-written loop using >. Every comparison with NaN is false, so such a loop silently skips NaN values, or keeps one, depending on where it appears.
console.log(Math.max(1, NaN, 3)); // NaN
console.log(Math.min(1, "abc", 3)); // NaN
console.log(Math.max(1, undefined)); // NaN (Number(undefined) is NaN)
console.log(Math.max(1, null)); // 1 (Number(null) is 0)
console.log(Math.max("10", "9")); // 10 (numeric, not string, comparison)
// Filter invalid values first if you want to ignore them
const raw = [4, NaN, 11, "7", undefined];
const valid = raw.map(Number).filter(Number.isFinite);
console.log(Math.max(...valid)); // 11Math.max("10", "9") returns 10 because the strings are converted to numbers. Comparing the same strings with > would compare them character by character and say "9" is greater.
Negative zero
Math.max and Math.min treat -0 as smaller than +0, unlike ===, which considers the two equal.
console.log(Object.is(Math.max(-0, 0), 0)); // true
console.log(Object.is(Math.min(0, -0), -0)); // trueThis rarely matters, but it means Math.min can hand back -0, which then displays as -0 in some contexts and produces -Infinity when you divide by it.
Very large arrays
Spreading passes every element as a separate function argument. Engines limit how many arguments a call can take. The limit depends on the engine and is often somewhere between tens of thousands and a few hundred thousand. Past it, the call throws a RangeError. For large or unbounded data, use a loop or reduce.
const big = Array.from({ length: 1_000_000 }, (_, i) => i);
// Math.max(...big) may throw RangeError: Maximum call stack size exceeded
const maxValue = big.reduce((acc, n) => Math.max(acc, n), -Infinity);
console.log(maxValue); // 999999Starting reduce at -Infinity gives the same empty-input behavior as Math.max(), and calling Math.max inside keeps the NaN and -0 rules.
Clamping a value
To clamp a value is to force it to stay inside a range. JavaScript has no built-in clamp function, but nesting min and max does the job.
function clamp(value, low, high) {
if (low > high) throw new RangeError("low must not exceed high");
return Math.min(Math.max(value, low), high);
}
console.log(clamp(150, 0, 100)); // 100
console.log(clamp(-20, 0, 100)); // 0
console.log(clamp(42, 0, 100)); // 42
console.log(clamp(NaN, 0, 100)); // NaNA NaN input passes straight through the clamp. If the value comes from user input, validate it with Number.isFinite before clamping.
Math.abs
Math.abs(x) returns the magnitude of x, its distance from zero. Like the others, it converts its argument first.
console.log(Math.abs(-5)); // 5
console.log(Math.abs("-5")); // 5
console.log(Math.abs(null)); // 0
console.log(Math.abs(undefined)); // NaN
console.log(Math.abs(-Infinity)); // Infinity
console.log(Object.is(Math.abs(-0), 0)); // trueMath.abs cannot overflow. In languages with fixed-width integers, the absolute value of the most negative integer does not fit in the type. JavaScript numbers are doubles with a sign bit, so Math.abs just clears that bit, and every finite input has a finite result.
The most common use is measuring the distance between two values, which is also the core of the tolerance comparison from the floating-point chapter:
function distance(a, b) {
return Math.abs(a - b);
}
console.log(distance(3, 10)); // 7
console.log(distance(10, 3)); // 7
function withinPercent(actual, expected, percent) {
return Math.abs(actual - expected) <= Math.abs(expected) * (percent / 100);
}
console.log(withinPercent(101, 100, 2)); // true
console.log(withinPercent(105, 100, 2)); // falseMath.sign
Math.sign(x) reports the sign of a number. It has five possible results, not three.
| Input | Result |
|---|---|
| Positive number, including `Infinity` | `1` |
| Negative number, including `-Infinity` | `-1` |
| `+0` | `0` |
| `-0` | `-0` |
| `NaN` or anything that converts to `NaN` | `NaN` |
console.log(Math.sign(42)); // 1
console.log(Math.sign(-0.001)); // -1
console.log(Math.sign("-3")); // -1
console.log(Math.sign(0)); // 0
console.log(Object.is(Math.sign(-0), -0)); // true
console.log(Math.sign("abc")); // NaNBecause Math.sign(-0) is -0, the check Math.sign(x) === 0 is true for both zeros, since -0 === 0. That is usually what you want. Use Object.is only if you really need to tell the zeros apart.
A useful pattern splits a number into sign and magnitude, changes the magnitude, and puts the sign back:
function roundHalfAwayFromZero(x) {
return Math.sign(x) * Math.round(Math.abs(x));
}
console.log(roundHalfAwayFromZero(2.5)); // 3
console.log(roundHalfAwayFromZero(-2.5)); // -3 (Math.round(-2.5) gives -2)Common errors at a glance
| Mistake | Symptom | Fix |
|---|---|---|
| `Math.max(array)` | `NaN`, or a correct value for one-element arrays | `Math.max(...array)` |
| Spreading an empty array | `-Infinity` or `Infinity` leaks into output | Check `length` first |
| One bad value in the data | Whole result is `NaN` | Filter with `Number.isFinite` |
| Spreading a huge array | `RangeError` | Use `reduce` or a loop |
| Assuming `Math.sign` returns only -1, 0, 1 | Unexpected `NaN` or `-0` | Validate input, use `Object.is` if needed |
Exercise
What does Math.min(...[]) return, and what does Math.max([10]) return? Explain each.
Show answer
Math.min(...[]) calls Math.min() with no arguments and returns Infinity, the identity value for a minimum. Math.max([10]) passes the array as one argument. It is converted to the string "10" and then to the number 10, so the result is 10. The correct answer here comes about by accident, and it would be NaN for an array with two or more elements.
Exercise
Write a function range(values) that returns the difference between the largest and smallest finite numbers in an array, ignoring non-numeric entries, and returns 0 if no valid numbers remain. Test it with [3, "8", NaN, -2, undefined].
Show answer
function range(values) { const nums = values.map(Number).filter(Number.isFinite); if (nums.length === 0) return 0; return Math.max(...nums) - Math.min(...nums); }. For [3, "8", NaN, -2, undefined] the valid numbers are 3, 8, and -2, so the result is 8 - (-2) = 10.
Exercise
Why does clamp(NaN, 0, 100) return NaN when clamp is written as Math.min(Math.max(value, low), high)?
Show answer
Math.max(NaN, 0) returns NaN because any NaN argument makes the result NaN. Then Math.min(NaN, 100) also returns NaN. The clamp never gets a chance to force the value into range, so you must validate the input before clamping.