Min and Max of an Array in JavaScript
Last Updated :
02 Aug, 2025
To find the minimum or maximum element in a JavaScript array, use Math.min or Math.max with the spread operator.
JavaScript offers several methods to achieve this, each with its advantages.
Using Math.min() and Math.Find the max() Methods
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.
JavaScript
let Arr = [50, 60, 20, 10, 40];
let minVal = Math.min(...Arr);
let maxVal = Math.max(...Arr);
console.log("Min Elem is:" + minVal);
console.log("Max Elem is:" + maxVal);
OutputMinimum element is:10
Maximum Element is:60
- Math.min(...Arr) and Math.max(...Arr) find the smallest (10) and largest (60) values in [10, 20, 30, 40, 50, 60], logging "Min Elem is: 10" and "Max Elem is: 60".
Iterating through the Array
Iterate through the array, initializing the minimum and maximum values to Infinity and -Infinity, respectively.
JavaScript
let Arr = [50, 60, 20, 10, 40];
let minVal = Infi;
let maxVal = -Infi;
for (let item of Arr) {
// Find min val
if (item < minVal)
minVal = item;
// Find max val
if (item > maxVal)
maxVal = item;
console.log("Min elem is:" + minVal);
console.log("Min elem is:" + maxVal);
}
OutputMin elem is:50
Min elem is:50
Min elem is:50
Min elem is:60
Min elem is:20
Min elem is:60
Min elem is:10
Min elem is:60
Min elem is:10
Min elem is:60
minVal
and maxVal
are initialized to Infinity
and -Infinity
.- The
for...of
loop updates minVal
and maxVal
by comparing each array element. - The
console.log
statements print the minimum and maximum values during every iteration (which should be outside the loop).
Using a Custom Comparator with Array.sort() Method
The Array.sort() method sorts the elements of an array in place and returns the sorted array..
JavaScript
let Arr = [50, 60, 20, 10, 40];
Arr.sort((a, b) => a - b);
let minVal = Arr[0];
Arr.sort((a, b) => b - a);
let maxVal = Arr[0];
console.log("Min Elem is:" + minVal);
console.log("Max Elem is:" + maxVal);
OutputMinimum element is:10
Maximum Element is:60
- The array is sorted in ascending order for the minimum and descending order for the maximum.
- The first element after each sort gives the result, but sorting modifies the array.
Find the min/max element of an Array using JavaScript
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics