Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Returning the highest value from an array in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers. Our function should iterate through the array and pick the greatest (largest) element from the array and return that element.
Using a Custom Loop Function
Here's a manual approach that iterates through the array to find the maximum value:
const arr = [5, 3, 20, 15, 7];
const findGreatest = (arr = []) => {
let greatest = -Infinity;
if (!arr?.length) {
return null;
}
for (let i = 0; i < arr.length; i++) {
const el = arr[i];
if (el > greatest) {
greatest = el;
}
}
return greatest;
};
console.log(findGreatest(arr));
20
Using Math.max() (Recommended)
JavaScript provides a built-in Math.max() method that's more concise and efficient:
const arr = [5, 3, 20, 15, 7]; // Using spread operator const maxValue = Math.max(...arr); console.log(maxValue); // Using apply method const maxValue2 = Math.max.apply(null, arr); console.log(maxValue2);
20 20
Using reduce() Method
The reduce() method provides a functional programming approach:
const arr = [5, 3, 20, 15, 7];
const maxValue = arr.reduce((max, current) => {
return current > max ? current : max;
}, -Infinity);
console.log(maxValue);
20
Handling Edge Cases
It's important to handle empty arrays and invalid inputs:
const findGreatest = (arr = []) => {
if (!Array.isArray(arr) || arr.length === 0) {
return null;
}
return Math.max(...arr);
};
console.log(findGreatest([])); // null
console.log(findGreatest([42])); // 42
console.log(findGreatest([1, 2, 3])); // 3
null 42 3
Comparison
| Method | Performance | Readability | Browser Support |
|---|---|---|---|
| Custom Loop | Good | Medium | All |
| Math.max() | Best | High | All |
| reduce() | Good | High | ES5+ |
Conclusion
Math.max(...array) is the most efficient and readable solution for finding the highest value. Use custom loops only when you need additional logic during iteration.
Advertisements
