EN
JavaScript - Math.min() method example
8
points
The Math.min()
function returns the smallest number from given numbers.
// ONLINE-RUNNER:browser;
var min = Math.min(2, 5);
console.log(min); // 2
console.log( Math.min(1) ); // 1
console.log( Math.min(1, 2) ); // 1
console.log( Math.min(1, 2, 3) ); // 1
console.log( Math.min(3, 25, -6, 0) ); // -6
console.log( Math.min(-5, -2, -7) ); // -7
console.log( Math.min(2, 1, NaN) ); // NaN
console.log( Math.min() ); // -Infinity
Math.min()
 function usage with an array in ES5 and ES6 example:
// ONLINE-RUNNER:browser;
var array = [7, 10, 5, 8];
// In ES5
console.log(Math.min.apply(Math, array)); // 5
// In ES6 - Spread Operator (...) has been introduced
console.log(Math.min(...array)); // 5
console.log(Math.min(100, ...array, 120, ...[151, 152])); // 5
1. Documentation
Syntax | Math.min(number1, number2, ...numbers) |
Parameters | number1, number2, ...numbers  - integer or float number values (primitive values). |
Result |
Minimal It returns It returns |
Description | min  is a static method that takes several arguments and returns the smallest value. |
2. Getting min value from array examples
2.1. With Array
reduce
method example
This approach uses reduce
method to find the minimum value inside an array. By making small modifications of Math.min(a, b)
 instruction we are able to find minimal value inside properties of a
 and b
 variables.
// ONLINE-RUNNER:browser;
var array = [1, 2, 3];
var result = array.reduce(function(a, b) {
return Math.min(a, b);
});
console.log(result); // 1
2.2. Recurrent min method example
This approach uses recurrence to find the minimum value inside the array or nested arrays.
// ONLINE-RUNNER:browser;
function findMin() {
function checkEntry(entry) {
if (entry instanceof Array) {
return findMin.apply(null, entry);
}
return entry;
}
if (arguments.length > 0) {
var result = checkEntry(arguments[0]);
for (var i = 1; i < arguments.length; ++i) {
var value = checkEntry(arguments[i]);
if (value < result) {
result = value;
}
}
return result;
}
return NaN;
}
console.log(findMin(1, 2, 3, [4, 5, 6],[7, 8, [9, 10]])); // 1
References
Â
Â