Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get minimum number without a Math function JavaScript
We need to find the smallest number from a set of numbers without using JavaScript's built-in Math.min() function. This requires implementing our own comparison logic.
Approach Using While Loop
We'll iterate through all numbers and keep track of the smallest value found so far, updating it whenever we encounter a smaller number.
Example
const numbers = [12, 5, 7, 43, -32, -323, 5, 6, 7, 767, 23, 7];
const findMin = (...numbers) => {
let min = Infinity, len = 0;
while(len < numbers.length) {
min = numbers[len] < min ? numbers[len] : min;
len++;
}
return min;
};
console.log(findMin(...numbers));
-323
Alternative Approach Using For Loop
A more straightforward implementation using a for loop:
const findMinWithFor = (...numbers) => {
let min = numbers[0];
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
return min;
};
console.log(findMinWithFor(25, 8, -15, 42, 3));
-15
How It Works
The algorithm compares each number with the current minimum value. If a smaller number is found, it becomes the new minimum. The function uses the spread operator (...) to accept any number of arguments.
Comparison
| Method | Readability | Performance |
|---|---|---|
| While loop | Moderate | Good |
| For loop | Better | Good |
Conclusion
Both approaches effectively find the minimum number without Math functions. The for loop version is more readable, while the while loop demonstrates manual index control.
