Find Minimum Value of an Array in JavaScript
What you’ll learn
- The classic linear scan: keep a running minimum and update it whenever you see a smaller element.
- A reusable
findMinfunction 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 smallest value stored, without sorting.
Live preview
Uses the same seven integers as example 1: 12, 5, 7, 3, 2, 8, 10.
📜 Pseudocode
function findMin(arr): // assume arr.length >= 1
min = arr[0]
for i from 1 to arr.length - 1:
if arr[i] < min:
min = arr[i]
return minAlgorithm
Goal: return the smallest element from an array of numbers in one pass.
Initialize
Set minVal = arr[0].
Scan
Loop from index 1 to the end of the array.
Update
If arr[i] < minVal, assign minVal = arr[i].
Return
Return minVal after the loop ends.
Find minimum (reference program)
function findMin(arr) {
let minVal = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < minVal) {
minVal = arr[i];
}
}
return minVal;
}
const array = [12, 5, 7, 3, 2, 8, 10];
const minValue = findMin(array);
console.log("Minimum value in the array: " + minValue);When every element is negative
function findMin(arr) {
let minVal = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < minVal) {
minVal = arr[i];
}
}
return minVal;
}
const negatives = [-9, -3, -1, -7];
console.log("Minimum (most negative): " + findMin(negatives));Notes
Parallel idea. Split large arrays into chunks, find each chunk minimum, then take minimum of partial results.
Data type. The same algorithm works for integers or floats; comparison edge cases can appear with values like NaN.
❓ FAQ
🔄 Input / output
These examples use fixed arrays. In real tasks, read values from form inputs, APIs, or files, then pass them to findMin.
Edge cases
arr.length === 0
No minimum exists; guard before reading arr[0].
arr.length === 1
The loop body does not run; the single element is the minimum.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Single scan | O(n) | O(1) |
Summary
- Algorithm: running minimum from left to right.
- Cost:
O(n)time,O(1)extra space. - Edge: define behavior for empty arrays before calling
findMin.
Finding the minimum in an unsorted list still needs only one left-to-right pass: O(n) time and O(1) extra space.
8 people found this page helpful
