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