Technical skill practice

JavaScript Math.max: Find a Value and Handle Empty or Invalid Inputs

Math.max selects a numeric maximum, not the record containing it. If the values come from an array, expand them deliberately and define what should happen for an empty or invalid collection.

The task

Get the maximum from a small sensor batch, then reject empty or nonfinite data before returning a result. Keep this value-only operation separate from selecting a sensor record.

Runnable Node 22 example

const assert = require('node:assert/strict');

assert.equal(Math.max(...[6, 14, 9]), 14);
assert.equal(Math.max(), -Infinity);
assert.equal(Number.isNaN(Math.max(6, NaN, 9)), true);
function maximum(values) {
  if (values.length === 0 || !Array.from(values).every(Number.isFinite)) return null;
  return Math.max(...values);
}
assert.equal(maximum([6, 14, 9]), 14);
assert.equal(maximum([]), null);
assert.equal(maximum([6, NaN]), null);
assert.equal(maximum(new Array(1)), null);
console.log(`maximum=${maximum([6, 14, 9])}; empty=${maximum([])}`);

Expected output and explanation

The built-in empty result is −Infinity, which is mathematically useful but may not be the intended output of a sensor summary. The wrapper deliberately uses null for no valid batch, preserving a distinction from an actual finite measurement.

NaN propagates through the unguarded maximum. The finite-value check prevents that result and also rejects infinities. Array.from materializes holes as undefined so a sparse input is rejected instead of being skipped by every. This rule assumes a list of numeric measurements, not textual values requiring a separate conversion policy.

Output from the example

maximum=14; empty=null

Pitfall to check

Expanding a huge array into function arguments can exceed engine limits. For large datasets, use an explicit incremental maximum with an appropriate input check. Also decide a tie policy if the caller needs the associated record rather than just the number.

Questions, answered

Does Math.max accept an array directly?

It accepts individual arguments. Use a deliberately bounded spread or an appropriate traversal; passing one array is not the same argument structure.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.