JavaScript Program to Find Smallest Element in Array
Math.min(...array) or by looping through the array and comparing elements to track the smallest value.Examples
How to Think About It
Algorithm
Code
const array = [3, 1, 4, 1, 5]; let smallest = array[0]; for (let i = 1; i < array.length; i++) { if (array[i] < smallest) { smallest = array[i]; } } console.log(smallest);
Dry Run
Let's trace the array [3, 1, 4, 1, 5] through the code to find the smallest element.
Initialize smallest
smallest = 3 (first element)
Compare with second element
1 < 3, so smallest = 1
Compare with third element
4 < 1? No, smallest stays 1
Compare with fourth element
1 < 1? No, smallest stays 1
Compare with fifth element
5 < 1? No, smallest stays 1
Return smallest
smallest = 1
| Iteration | Current Element | Smallest So Far |
|---|---|---|
| 1 | 3 | 3 |
| 2 | 1 | 1 |
| 3 | 4 | 1 |
| 4 | 1 | 1 |
| 5 | 5 | 1 |
Why This Works
Step 1: Start with first element
We assume the first element is the smallest to have a starting point for comparison.
Step 2: Compare each element
We check each element to see if it is smaller than the current smallest value.
Step 3: Update smallest value
If a smaller element is found, we update the smallest value to that element.
Step 4: Return the smallest
After checking all elements, the smallest value holds the smallest element in the array.
Alternative Approaches
const array = [3, 1, 4, 1, 5]; const smallest = Math.min(...array); console.log(smallest);
const array = [3, 1, 4, 1, 5]; const smallest = array.reduce((min, current) => current < min ? current : min, array[0]); console.log(smallest);
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 method and reduce have similar performance; Math.min is concise but may be slower or limited on very large arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop with if | O(n) | O(1) | Large arrays, simple logic |
| Math.min with spread | O(n) | O(n) | Small to medium arrays, concise code |
| Array.reduce | O(n) | O(1) | Functional style, readability |
Math.min(...array) for quick and simple smallest element retrieval in small to medium arrays.