Math.max.apply() not working inside of a for loop

Math.max.apply() not working inside of a for loop


Why isn’t my code working? Math.max isn’t returning anything.

function largestOfFour(arr) {
  var newArray = {}
  // You can do this!
  for (x = 0 ; x < arr.length;x++){
    Math.max.apply(Math, arr[x]) 
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);




Try Math.max.apply(null, arr[x])


As lorepieri points out, that is the way to get it to work, as for the reason why…

Math.max() accepts a list of values, like:

var a = Math.max(12, 6, 18, 5);

But in your code, you’re not sending it a list of values, you’re sending it an array of values. That is a big difference.

So, that raises the question: How do you get Math.max() to work with an array? Just do what lorepieri says. Yes, the first argument is null - don’t let it bother you, the why of that isn’t important at your level.


The documentation explains it pretty well, including using the spread operator (es2015)


Wow, that spread operator makes it easier, for sure!