EN
JavaScript - Math.max() method example
11 points
The Math.max()
function returns the highest number from given numbers.
xxxxxxxxxx
1
var max = Math.max(2, 5);
2
console.log( max ); // 5
3
4
console.log( Math.max(1) ); // 1
5
console.log( Math.max(1, 2) ); // 2
6
console.log( Math.max(1, 2, 3) ); // 3
7
console.log( Math.max(3, 25, -6, 0) ); // 25
8
9
console.log( Math.max(-5, -2, -7) ); // -2
10
console.log( Math.max(2, 1, NaN) ); // NaN
11
console.log( Math.max() ); // -Infinity
Math.max()
function usage with an array in ES5 and ES6 example:
xxxxxxxxxx
1
var array = [10, 5, 0];
2
3
// In ES5
4
console.log( Math.max.apply(Math, array) ); // 10
5
6
// In ES6 - Spread Operator (...) has been introduced
7
console.log( Math.max(array) ); // 10
8
console.log( Math.max(100, array, 120, [151, 152]) ); // 152
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. |
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.
xxxxxxxxxx
1
var array = [1, 2, 3];
2
3
var result = array.reduce(function(a, b) {
4
return Math.max(a, b);
5
});
6
7
console.log(result); // 3
This approach uses recurrence to find the maximum value inside an array of nested arrays.
xxxxxxxxxx
1
function findMax() {
2
function checkEntry(entry) {
3
if (entry instanceof Array) {
4
return findMax.apply(null, entry);
5
}
6
7
return entry;
8
}
9
10
if (arguments.length > 0) {
11
var result = checkEntry(arguments[0]);
12
13
for (var i = 1; i < arguments.length; ++i) {
14
var value = checkEntry(arguments[i]);
15
16
if (value > result) {
17
result = value;
18
}
19
}
20
21
return result;
22
}
23
24
return NaN;
25
}
26
27
console.log(findMax(1, 2, 3, [4, 5, 6],[7, 8, [9, 10]])); // 10