Find Maximum Value of an Array in JavaScript
What you’ll learn
- The classic linear scan: keep a running maximum and update it whenever you see a larger element.
- A reusable
findMaxfunction and safe handling ideas for empty arrays. - A second example with all negative values, plus a live preview and Try it editors.
Overview
You walk the array once. The answer after visiting every slot is the largest value stored, without sorting.
Live preview
Uses the same six integers as example 1: 14, 7, 25, 31, 10, 42.
📜 Pseudocode
function findMax(arr): // assume arr.length >= 1
max = arr[0]
for i from 1 to arr.length - 1:
if arr[i] > max:
max = arr[i]
return maxAlgorithm
Goal: return the largest element from an array of numbers in one pass.
Initialize
Set maxVal = arr[0].
Scan
Loop from index 1 to the end of the array.
Update
If arr[i] > maxVal, assign maxVal = arr[i].
Return
Return maxVal after the loop ends.
Find maximum (reference program)
function findMax(arr) {
let maxVal = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
return maxVal;
}
const array = [14, 7, 25, 31, 10, 42];
const maxValue = findMax(array);
console.log("Maximum value in the array: " + maxValue);When every element is negative
function findMax(arr) {
let maxVal = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
return maxVal;
}
const negatives = [-9, -3, -1, -7];
console.log("Maximum (least negative): " + findMax(negatives));Notes
Parallel idea. Split large arrays into chunks, find each chunk max, then take max of partial results.
Data type. The same algorithm works for integers or floats; only comparison behavior differs for special values like NaN.
❓ FAQ
🔄 Input / output
These examples use hard-coded arrays. In real tasks, read values from form inputs, API responses, or files, then pass them to findMax.
Edge cases
arr.length === 0
No maximum exists; guard before reading arr[0].
arr.length === 1
The loop body does not run; the single element is the maximum.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Single scan | O(n) | O(1) |
Summary
- Algorithm: running maximum from left to right.
- Cost:
O(n)time,O(1)extra space. - Edge: define behavior for empty arrays before calling
findMax.
Finding the maximum in an unsorted array needs at least n − 1 comparisons in the worst case. A single left-to-right scan achieves O(n) time and O(1) extra space.
8 people found this page helpful
