Understanding JavaScript’s Math.max: Edge Cases and Array Tricks
This article explains how JavaScript’s Math.max function works, covering typical usage, single‑argument behavior, the surprising -Infinity result when called without arguments, and practical techniques for finding maximum values in arrays, including handling empty arrays.
Math.max is a built‑in JavaScript function that returns the largest value from a given set of numbers.
Syntax: Math.max(value1[, value2, ...]) Example with multiple arguments: Math.max(1, 2, 3); // => 3 When called with a single argument, the function simply returns that argument: Math.max(1); // => 1 If no arguments are provided, Math.max returns -Infinity, which represents the lowest possible numeric value.
Maximum of an array
You can find the maximum number in an array by using the spread operator:
const numbers1 = [1, 2, 3];
Math.max(...numbers1); // => 3Maximum of two arrays
To compare the maximum values of two arrays, compute each maximum first and then compare them:
const numbers1 = [1, 2, 3];
const numbers2 = [0, 6];
const max1 = Math.max(...numbers1);
const max2 = Math.max(...numbers2);
Math.max(max1, max2); // => 6If one of the arrays is empty, spreading it yields no arguments, so Math.max(...[]) behaves the same as Math.max() and returns -Infinity:
const numbers1 = [];
const numbers2 = [0, 6];
const max1 = Math.max(...numbers1); // -Infinity
const max2 = Math.max(...numbers2); // 6
Math.max(max1, max2); // => 6Similarly, Math.min() with no arguments returns Infinity, making the statement Math.min() > Math.max() evaluate to true.
Visual summary:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
