Find the range of a list of numbers in JavaScript
Beginner · 4 min read
The range of a list of numbers is the gap between the largest and the smallest. For marks of 61 to 95 the range is 34. It is the simplest measure of spread: a daily temperature range, the spread of prices for one product, the gap between the fastest and slowest lap.
In code, it is one line with Math.max and Math.min. But those two functions have surprises at the edges: what they return for an empty list, what one NaN does, and what happens when the list is very long. In this tutorial you will write range(xs), test each edge, and write a reduce version that works for lists of any length. You need to know arrays and arrow functions.
Spreading an array into arguments
Math.min and Math.max don't take an array. They take separate arguments: Math.min(3, 1, 2). To pass an array, you spread it with ..., which unpacks it into separate arguments:
const xs = [3, 1, 2];
console.log(Math.min(...xs)); // 1
console.log(Math.max(...xs)); // 3
Math.min(...xs) is the same as writing Math.min(3, 1, 2).
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
59 The range, and the minimum of nothing
easyFind the smallest, the largest and the spread between them. Then check what Math.min() returns with no arguments, what one NaN in the list does, and use reduce on a list too long to spread.
Stuck? Three hints, smallest first
- 1.
Math.min(...xs)spreads the list into arguments, and there is a limit to how many. - 2.
Math.min()with nothing to compare returns the identity for minimum, which isInfinity. - 3.
Math.min(1, NaN)isNaN: one bad reading poisons the answer.
Step 1: min, max and range
const range = (xs) => Math.max(...xs) - Math.min(...xs);
const marks = [72, 88, 61, 95, 79];
console.log(Math.min(...marks), Math.max(...marks)); // 61 95
console.log(range(marks)); // 34
console.log(range([42])); // 0
95 minus 61 is 34. A list with one value has a range of 0, since the largest and smallest are the same number.
Step 2: the range of nothing
console.log(Math.min()); // Infinity
console.log(Math.max()); // -Infinity
console.log(range([])); // -Infinity
With nothing to compare, Math.min() returns Infinity and Math.max() returns -Infinity. That looks backwards, but there is a reason. Think of Math.min as starting with "the smallest so far" and lowering it as it sees values. The only safe starting point, before seeing anything, is a value larger than every possible number: Infinity. With no values to see, that starting point is what comes back.
So the range of an empty list is -Infinity minus Infinity, which is -Infinity. No report should print that. Check for an empty list yourself before calling range.
Step 3: one NaN spoils everything
console.log(Math.min(...[1, NaN, 3])); // NaN
console.log([1, NaN, 3].filter(Number.isFinite)); // [ 1, 3 ]
If any value is NaN, for example a sensor reading that failed to parse, Math.min returns NaN. It doesn't skip bad values. Number.isFinite is false for NaN and for Infinity, so filtering with it leaves only usable numbers. Clean the list first, then summarize it.
Step 4: min and max with reduce
The spread passes every item as a separate argument, and JavaScript engines limit how many arguments a call can have. To avoid that limit, walk the list with reduce instead:
const minOf = (xs) => xs.reduce((a, b) => (b < a ? b : a), Infinity);
const maxOf = (xs) => xs.reduce((a, b) => (b > a ? b : a), -Infinity);
console.log(minOf(marks), maxOf(marks)); // 61 95
minOf starts at Infinity and keeps whichever is smaller, the running minimum a or the next item b. maxOf does the opposite. They start from the same values Math.min() and Math.max() return for nothing, so an empty list gives the same answers as before.
One difference: minOf([1, NaN, 3]) gives 1, not NaN, because any comparison with NaN is false, so NaN is never kept. That hides bad data rather than flagging it, so filtering first is still the right habit.
Step 5: a very long list
const big = Array.from({ length: 100000 }, (_, i) => (i * 7919) % 100000);
console.log(minOf(big), maxOf(big)); // 0 99999
big holds the numbers 0 to 99999 in a jumbled order. reduce handles it easily, and it would handle ten million values just the same. The spread version has a ceiling, and the exact ceiling depends on the engine. In node, spreading ten million values fails:
try {
Math.max(...new Array(10000000).fill(1));
} catch (e) {
console.log(e.message); // Maximum call stack size exceeded
}
That is node's message; browsers may word it differently and may fail at a different size. Don't build on where the limit is. Use reduce for lists that can grow.
Step 6: zero and minus zero
console.log(Object.is(Math.min(0, -0), -0)); // true
console.log(Object.is(Math.max(0, -0), 0)); // true
JavaScript has a separate minus zero, -0. It equals 0 with ===, but Math.min treats it as the smaller of the two and Math.max as the larger. Object.is is a comparison that can tell them apart. You will rarely need this, but it explains a -0 if one ever shows up in your output.
The full solution
The answer panel has range, minOf and maxOf, then prints the marks' min, max and range, the reduce results, the no-argument cases, the empty range, the NaN case, the 100000-value list and the zero case. Press Run to see the output.
const range = (xs) => Math.max(...xs) - Math.min(...xs);
// No spread, so no argument limit.
const minOf = (xs) => xs.reduce((a, b) => (b < a ? b : a), Infinity);
const maxOf = (xs) => xs.reduce((a, b) => (b > a ? b : a), -Infinity);
const marks = [72, 88, 61, 95, 79];
const big = Array.from({ length: 100000 }, (_, i) => (i * 7919) % 100000);
console.log('min, max, range:', Math.min(...marks), Math.max(...marks), range(marks));
console.log('reduce agrees :', minOf(marks), maxOf(marks));
console.log('no arguments :', Math.min(), Math.max());
console.log('so empty range :', range([]));
console.log('one NaN :', Math.min(...[1, NaN, 3]));
console.log('100000 values :', minOf(big), maxOf(big));
console.log('0 and -0 :', Math.min(0, -0), 'which is minus zero:', Object.is(Math.min(0, -0), -0));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the marks run from 61 to 95, a range of 34', [Math.min(...marks), Math.max(...marks), range(marks)], [61, 95, 34]);
test('reduce gives the same two numbers with no spread', [minOf(marks), maxOf(marks)], [61, 95]);
test('Math.min() is Infinity and Math.max() is -Infinity', [Math.min() === Infinity, Math.max() === -Infinity], [true, true]);
test('so the range of an empty list is -Infinity, not 0', range([]) === -Infinity, true);
test('a single NaN in the list poisons the minimum', Number.isNaN(Math.min(...[1, NaN, 3])), true);
test('reduce handles 100000 values, which a spread may refuse', [minOf(big), maxOf(big)], [0, 99999]);
test('Math.min(0, -0) returns minus zero, and Math.max returns plus', [Object.is(Math.min(0, -0), -0), Object.is(Math.max(0, -0), 0)], [true, true]);
test('a one-value list has a range of 0', range([42]), 0);
Math.min() returning Infinity is not a quirk, it is the identity element: the minimum of nothing has to be larger than everything for min(a, min()) to equal a. It does mean the range of an empty list is -Infinity, which no report wants to print, so guard the empty case yourself.
Math.min(...xs) passes every element as a separate argument. That is fine for a hundred values and fails for a hundred thousand — the engine's argument limit is not part of the language, so where exactly it breaks is not something to build on. reduce has no such ceiling. And note the NaN: Math.min does not skip it, so filter your readings before you summarise them.
Common mistakes
- Not checking for an empty list.
range([])is-Infinity, not 0. - Leaving
NaNin the data. OneNaNmakesMath.minandMath.maxreturnNaN. Filter withNumber.isFinitefirst. - Spreading huge arrays. Engines limit the number of arguments. Use
reducefor long lists.
Try it yourself
- Write
safeRange(xs)that returnsnullfor an empty list and ignores values that aren't finite. - Find the range of the temperatures
[31, 24, 29, 35, 22], then of the list withNaNadded. - Write
minMax(xs)that finds both values in a singlereduceand returns{ min, max }.