How to use Math.min() and Math.max() Methods In Javascript
The Math object’s Math.min() and Math.max() methods are static methods that return the minimum and maximum elements of a given array. The spread(…) operator could pass these functions into an array. The spread operator allows an iterable to expand in places where multiple arguments are expected. In this case, it automatically expands the array and gives the numbers to the functions.
Syntax:
minValue = Math.min(...array);
maxValue = Math.max(...array);
Example: We will see the basic implementation of JavaScript Math.min() and Math.max() methods.
function findMinMax() {
let Arr = [50, 60, 20, 10, 40];
let minValue = Math.min(...Arr);
let maxValue = Math.max(...Arr);
console.log("Minimum element is:" + minValue);
console.log("Maximum Element is:" + maxValue);
}
findMinMax()
Output
Minimum element is:10 Maximum Element is:60
Find the min/max element of an Array using JavaScript
Finding the minimum or maximum element of an array in JavaScript involves determining the smallest or largest value from the array’s elements. This operation is crucial for various tasks, such as data analysis, optimization problems, and comparisons within algorithms.
The minimum and maximum elements in an array can be found using the following methods:
Table of Content
- Using Math.min() and Math.max() Methods
- Iterating through the Array
- Using JavaScript Array.reduce() method
- Using apply method
- Using spread operator