Home
IT Knowledge
Inspiration
Languages
EN

# JavaScript - Math.min() method example

8 points
Created by:
10090

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 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 `number` value (primitive value). It returns `Infinity` if no arguments are passed. It returns `NaN` if at least one of the provided values is not a number. Description `min` is static method that takes number arguments and returns the smallest one value.

## 2. Getting min value from array examples

### 2.1. With `Array``reduce` method example

This approach uses `reduce` method to find minimum value inside array. By making small modification 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 minimum value inside 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

1. Maxima and minima - Wikipedia