No, you can't really solve that problem with .call()
. It just doesn't do what you want.
.call()
requires you to pass each argument to the host function individually. So, you could only use Math.max()
to find the maximum value in an array if you knew ahead of time exactly how many items would be in the array or if you coded for all possible lengths. Basically, the situation where the arguments are in an arbitrary length array is what .apply()
is built for, not what .call()
is built for.
Further, if you can manually pass the arguments as .call()
requires and you aren't trying to set a custom this
value, then there's really no reason to use .call()
at all, you may as well just call the function directly without .call()
. So, I can't find any reason to use .call()
for this particular problem.
Here's some more info written about .call()
and .apply()
from a couple days ago, including info about using .apply()
with Math.max()
for this particular issue.
To look at your specific example:
var numbers = [2,3,56,7,1];
var max = Math.max.apply(null,numbers);
console.log(max); //output 56
If you wanted to not use .apply()
, then you could do either of these:
var numbers = [2,3,56,7,1];
var max = Math.max(2,3,56,7,1);
or
var numbers = [2,3,56,7,1];
var max = Math.max.call(Math, 2,3,56,7,1);
But, as you can see the .call()
example adds no value at all over just calling the function directly because you aren't trying to set a custom this
value AND both examples require explicitly naming each argument so they don't work with an array whose length is not known ahead of time when you write the code. This example is built exactly for .apply()
, not for .call()
. This is why we have both options because they are built for different situations.
Note that with ES6, you can use the spread operator which is a shorthand for passing arguments like .apply()
does without the custom this
value:
var numbers = [2,3,56,7,1];
var max = Math.max(...numbers);
And it will solve the problem for you.