Home Communities
IT Knowledge
Inspiration
Languages
EN

# JavaScript - Math.min() method example

8 points
Created by:
473

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Â 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 a static method that takes several arguments and returns the smallest value.

## 2. Getting min value from arrayÂ examples

### 2.1. With Arrayreduce 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

1. Maxima and minima - Wikipedia

Â

Â

## Alternative titles

Join to our subscribers to be up to date with content, news and offers.