JavaScript Program to Find Largest Element in Array
Math.max(...array) or by looping through the array and comparing elements with a variable holding the current largest value.Examples
How to Think About It
Algorithm
Code
const arr = [3, 5, 1, 9, 2]; let largest = arr[0]; for (let i = 1; i < arr.length; i++) { if (arr[i] > largest) { largest = arr[i]; } } console.log(largest);
Dry Run
Let's trace the array [3, 5, 1, 9, 2] through the code to find the largest element.
Initialize largest
largest = 3 (first element)
Compare with second element
5 > 3, so largest = 5
Compare with third element
1 > 5? No, largest stays 5
Compare with fourth element
9 > 5, so largest = 9
Compare with fifth element
2 > 9? No, largest stays 9
Return largest
largest = 9
| Iteration | Current Element | Largest Value |
|---|---|---|
| 1 | 3 | 3 |
| 2 | 5 | 5 |
| 3 | 1 | 5 |
| 4 | 9 | 9 |
| 5 | 2 | 9 |
Why This Works
Step 1: Start with first element
We assume the first element is the largest to have a starting point for comparison.
Step 2: Compare each element
We check each element using if (arr[i] > largest) to find if it is bigger than the current largest.
Step 3: Update largest value
When a bigger element is found, we update the largest variable to hold this new value.
Step 4: Return the largest
After checking all elements, the largest variable holds the biggest number in the array.
Alternative Approaches
const arr = [3, 5, 1, 9, 2]; const largest = Math.max(...arr); console.log(largest);
const arr = [3, 5, 1, 9, 2]; const largest = arr.reduce((max, current) => current > max ? current : max, arr[0]); console.log(largest);
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once, so the time grows linearly with the array size, making it O(n).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
The loop and Math.max approaches both run in O(n) time, but Math.max may be slower for very large arrays due to spreading.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop with variable | O(n) | O(1) | Clear logic and large arrays |
| Math.max with spread | O(n) | O(n) | Short code and small to medium arrays |
| Array.reduce | O(n) | O(1) | Functional style and chaining |
Math.max(...array) for a quick and simple way to find the largest element.