Javascript Math.min and Math.max Functions – A Better Approach

Javascript Math.min and Math.max Functions – A Better Approach

Javascript provides several Functions to solve solutions, one of them is Math.min() and Math.max(). We can start by asking, what exactly does Math.min() and Math.max() functions do? How can we use it in our code? How does it work, and all? Read this article further to answer your questions.

Basically, the Math.min() function returns the lowest-valued number passed into it. While, the Math.max() functions return the highest-valued number passed.

Example:

This returns the lowest-valued number passed

let minNumber = (2, 4, 8, 9, 3);
console.log(Math.min(minNumber)); // 2

This returns the highest-valued number passed

let maxNumber = (1, 2, 4, 8, 9, 3);
console.log(Math.max(maxNumber)); // 9

Although there are other ways to find the minimum or maximum value from an array in Javascript, we will be restricted to Math.min() and Math.max() functions in this article.

Using Math.min() and Math.max() for Number From the examples shown above, it is clear that the parameters being passed are numbers. Therefore, for us to be able to use min or max functions, we should only pass the number parameter. A quick checkout again;

console.log(Math.min(8, 3, 6)); // 3
console.log(Math.max(-4, -8, -2)); // -1

Using Math.min() and Math.max() for Array

What happens if we want to pass an array as a parameter?

When we pass an array as a parameter to Math.min() and Math.max(), we get NaN (Not a Number) as result.

Example;

console.log(Math.min([8, 3, 6]); // NaN
console.log(Math.max(-4, -8, -2)); // NaN

This occurs because the function only expects a number, a value being passed, and not an array. Before ES6/ES2015, we can achieve the min and max value of a parameter using the apply method alongside. Sample below;

let myNums = [2, 8, 4, 3, 7]
console.log(Math.min.apply(Math, myNums)); // 2

let myNums = [2, 8, 4, 3, 7]
console.log(Math.max.apply(Math, myNums)); // 8

Although this is possible, with ES6/ES2015, there is a simpler and concise way to use the min() and max() method which is, making use of the Spread Operator (…array) in our array. See sample below

let myNums = [2, 8, 4, 3, 7];
console.log(Math.min(...myNums)); // 2

let myNums = [2, 8, 4, 3, 7];
console.log(Math.max(...myNums)); // 8

In this case, what the spread operator does is that it converts our array to distinct variables/ numbers and sends them to the functions. We should note that using (…myNums) is equivalent to (2, 8, 4, 3, 7).

Conclusion

Despite the fact that there are other ways to return the lowest or highest valued number passed, the most convenient and concise approach is using the syntax Math.min(...array) and Math.max(...array) - the ES6’s spread operator (…). Now go find some minimums and maximums!

Thanks for reading guys, if you find this insightful, kindly post a comment, share, like and follow. I will continue to share excellent content.