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 will always return the largest number. For example, in the console:
Math.max(5, 10, 11, 3, 22); > 22
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)
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 (
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:
Alternatively (and with greater browser support), use
apply to achieve the same result:
apply technique can also be used with
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.