The maximum is the largest element in the array. For an unsorted array, scan once from left to right and keep a running best.
Remember
arr = [12, 45, 7, 42, 19]
max = 45
Idea:
max = arr[0]
for each later element x:
if x > max → max = x
Works for negatives too:
[-8, -1, -15] → max = -1
Array
Maximum
[12, 45, 7, 42, 19]
45
[-8, -1, -15]
-1
[5]
5
[]
undefined — handle empty
Approach
How to Find the Maximum in JavaScript
Four clear steps — one linear pass is enough.
Reject an empty array (no maximum exists).
Set max = arr[0] as the first candidate.
Loop from index 1 to the end.
Whenever arr[i] > max, update max (optionally track the index too).
Method
Idea
Time
Best for
Linear scan
Running maximum with >
O(n)
Interviews, unsorted arrays
Track index
Same scan, also store the position
O(n)
When you need where the max is
Pseudocode
Pseudocode
function FindMax(arr):
if length(arr) == 0:
error "empty array"
max = arr[0]
for i from 1 to length(arr) - 1:
if arr[i] > max:
max = arr[i]
return max
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Start
max = arr[0]
Update
if arr[i] > max
Empty
Validate before reading arr[0]
Negatives
Still use > — do not assume positive
Avoid
Sorting just to get the max
Classic check
[12, 45, 7, 42, 19] → 45
Try it
Live Preview
Pick a sample array to see the running maximum after each step.
Tap a chip to run the linear scan trace.
Result
arr = [12, 45, 7, 42, 19]
start max = 12
45 > 12 → max = 45
7 ≤ 45
42 ≤ 45
19 ≤ 45
Maximum = 45
Code
JavaScript Programs
Start with a simple running maximum. Then track the index when you also need the position.
Example 1 — Linear Scan
Keep a running maximum and update it whenever a larger element appears.
JavaScript
function findMax(arr) {
if (!arr || arr.length === 0) {
throw new Error("Array must not be empty.");
}
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
const numbers = [12, 45, 7, 42, 19];
console.log("Maximum = " + findMax(numbers));
Reject empty (or missing) arrays before reading arr[0].
Seed max with the first element.
Loop from index 1 so you never compare the seed against itself needlessly.
Update when arr[i] > max.
Return the final running maximum after one pass.
Example 2 — Track Index
Same scan, but also remember the first index where the maximum appears.
JavaScript
function findMaxIndex(arr) {
if (!arr || arr.length === 0) {
throw new Error("Array must not be empty.");
}
let maxIndex = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
const numbers = [12, 45, 7, 42, 19];
const index = findMaxIndex(numbers);
console.log("Max = " + numbers[index] + " at index " + index);