Languages
[Edit]
EN

JavaScript - Math.max() method example

11 points
Created by:
Marcin
15740

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 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

SyntaxMath.max(number1, number2, ...numbers)
Parametersnumber1, number2, ...numbers - integer or float number values (primitive values).
Result

Maximal 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.

Descriptionmax is static method that takes number arguments and returns the biggest one value.

2. Getting max value from array examples

2.1. With Array reduce method example

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

References

  1. Maxima and minima - Wikipedia

JavaScript - Math (EN)

Native Advertising
50 000 ad impressions - 449$
ūüöÄ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

‚̧ԳŹūüíĽ ūüôā

Join