Table of Contents
Introduction to JavScript math max() method
Comparison is at the heart of “almost” everything we do, and with numerical values, they are needed to carry out certain operations. We need to know the maximum or the minimum value within a sequence or series of numbers for certain applications.
Math object that allows us to achieve this, and more specifically, we can find the highest or largest value using the Math
Using the Math
As stated earlier, the
Math.max() method returns the largest of the series of numbers that are passed as an argument. Using the
Math max method, we can try three approaches - normal arguments, the
reduce method and the
spread operator - to make use of the Math
Using normal arguments
We can pass all the numbers we want to compare to the
Math.max method to find the highest or largest value among them
console.log(Math.max(12, 3, 4, 5, 67, 321, 121212));
Though this is simple, it can be unrealistic when dealing with a large set of numbers probably stored within an array, and that’s where the
spread operator comes in.
spread operator allows expanding all the elements of an iterable such as an array as arguments to functions. So, with these, we can pass all the elements of the array to the
const arr = [ 12, 34, 56, 7, 121, 12212, 12, 2345, 34565, 454, 343, 3432, 778, 454, ]; const highElement = Math.max(...arr); console.log(highElement);
reduce method is a higher-order function that takes a callback function that works on each element where an operation is done in relation to the preceding element to result in a single value. So in our case, the operation that will be done will be the
Math.max() method call.
To illustrate, we will apply the
Math.max() method on the current element and its preceding element by find the highest value between the two values via the
reduce method till we return the highest across all the elements in the array.
const arr = [ 12, 34, 56, 7, 121, 12212, 12, 2345, 34565, 454, 343, 3432, 778, 454, ]; const max = arr.reduce((a, b) => Math.max(a, b)); console.log(max);
So, instead of using the
spread operator, we use the
reduce method to apply the
Math.max() method on two numbers (the preceding highest element, and the current element) at a time. Note that at the start of the
reduce method, the preceding element is
-Infinity which is considered the lowest number automatically (we can define it in our expression statement but it’s optional).
spread operator, and the