Streaks of red light on a road, caught in a long-expose photograph

この記事は日本語に翻訳されています。

Being confronted with a series of numbers and having to find the largest or smallest in the set is a common coding task. While it’s entirely possible to use a mathematical operator in JavaScript to find an answer, or even a series of if statements, the Math.max function (and it’s opposite, Math.min) are more effective and efficient.

Unlike functions that you write for yourself, Math.max is a “built-in” function in JavaScript that you can use natively. Given a series of numbers os arguments, Math.max will always return the largest number. For example, in the console:

Math.max(5, 10, 11, 3, 22);
> 22

Note that Math.max can also take variables, or object properties:

let orbitalPeriod = new Object();
orbitalPeriod.Mercury = 87.97,
orbitalPeriod.Venus = 224.70,
orbitalPeriod.Mars = 686.98;
Math.max(orbitalPeriod.Mercury, orbitalPeriod.Venus, orbitalPeriod.Mars)
> 686.98

One thing it can’t do is automatically find the largest value in an array. This has traditionally required looping, comparing each value and preserving the greater. For browsers that support ES6, the spread operator is far more succinct:

let orbitalPeriods = [87.97, 224.70, 686.98],
longestOrbit = Math.max(... orbitalPeriods);

Math.max is often used to create an “either / or” result for some comparison. For example, if you were looking at screen sizes:

let screenWidth = (screen.width, 0)

The screenWidth variable, assigned via let, must resolve to a number: either the width of the screen or (if that test was unsuccessful, and does not yield a number) 0.

Hitting the Lower Limit

Math.min is the opposite: given a series of values, .min finds the smallest.

Math.min(0.139, 0.15, 1);
> 0.139

Math.min is often used for setting or determining boundary conditions. For example, let’s say we have a ball bouncing inside a rectangular area. The right side of the rectangle is at 500 pixels; in a collision state with the ball, we want to the right side of the ball (ball.right) to be no further than the right side of the rectangle (500).

let collide = Math.min(ball.right,500);

Again, you can use spread to “distribute” the values in an array into the Math.min function. Given an array bugSizes, to find the smallest insect:

Math.min(...bigSizes)

Alternatively (and with greater browser support), use apply to achieve the same result:

Math.min.apply(null, bigSizes);

Like spread, the apply technique can also be used with Math.max.

Photograph by Iko, used under a Creative Commons Attribution-NonCommercial-NoDerivs 2.0 Generic license

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.