JavaScrpt Math.max() and Math.min for Arrays

To find the max or min values from an array in JavaScriput, one does not need to reinvent the wheel, just use the native Math.max() or Math.min() methods. 

Problem

The problem with the native Math.max() or Math.min() methods is that they take in numbers not an array. If you put in an array, the return value is NaN.

Solution

The solution to this problem is to enter in the array using the dot operator.

Example

var arr = [1,2,3,4];
console.log(Math.max(arr));
//NaN
console.log(Math.max(...arr));
//4

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser