Arrays and algorithms · beginner
JavaScript Program to Find the Largest Element in an Array
Find the largest number in a JavaScript array with a loop, with Math.max(...array) and with reduce(), and find the second largest even when the maximum repeats.
- for...of
- Math.max() and spread
- reduce()
- Set
Finding the largest value by hand teaches the "best so far" pattern: keep the best value seen and replace it when a bigger one comes along. The same pattern finds the cheapest price or the longest word.
The second largest number is a common follow-up with a trap: in [8, 3, 8, 5] the answer is 5, not 8.
The program
const numbers = [42, 7, 93, 18, 93, 64];
let largest = numbers[0];
for (const n of numbers) {
if (n > largest) largest = n;
}
console.log("Largest:", largest);
let second = -Infinity;
for (const n of numbers) {
if (n < largest && n > second) second = n;
}
console.log("Second largest:", second);Largest: 93
Second largest: 64How it works
- largest starts as the first element, so arrays of negative numbers work too.
- Every element bigger than the best so far replaces it.
- For the second largest, only values smaller than the largest count, so the second 93 is ignored.
- second starts at -Infinity, which is smaller than every number; it stays -Infinity when there is no second distinct value.
Watch it run line by line
Watch largest change from 42 to 93 and then stay put, even when the second 93 arrives. In the second loop, second goes -Infinity → 42 → 64.
“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Math.max with spread, and reduce()
Math.max(...numbers) is the shortest way. For very large arrays (hundreds of thousands of elements), spreading can exceed the argument limit, and reduce() is safer. For the second largest, a Set removes duplicates before sorting.
const numbers = [42, 7, 93, 18, 93, 64];
console.log(Math.max(...numbers));
console.log(numbers.reduce((a, b) => (b > a ? b : a)));
console.log([...new Set(numbers)].sort((a, b) => b - a)[1]);93
93
64Common mistakes
- Starting with largest = 0, which is wrong for an array like [-5, -2, -9].
- Calling sort() without a compare function: [10, 9, 100].sort() gives [10, 100, 9], because elements are compared as strings.
- Math.max(numbers) without the spread returns NaN.
- reduce() on an empty array without an initial value throws TypeError.
Try it yourself
- Also print the index of the largest element with indexOf().
- Find the smallest and largest values in one pass.
Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.