John Anisere John Anisere - 26 days ago 11
Javascript Question

Someone please explain the Function.apply.bind(Math.max, null) algorithm

suppose we have this code

function largestOfFour(arr) {
return arr.map(Function.apply.bind(Math.max, null));
}


where arr is an array of arrays.


  1. first,why must i use apply()?



I understand that when using the method Math.max() to operate on an array i must add the apply() method also. So i'll have something like this
Math.max.apply(null, arr)
why? what does apply() do?


  1. In this code
    arr.map(Function.apply.bind(Math.max, null))
    what does bind() really do?



Please give an explanation i can understand,i really appreciate this.

Answer Source

Looking at the entire expression:

arr.map(Function.apply.bind(Math.max, null));

map expects its first argument to be a function, which is returned by:

Function.apply.bind(Math.max, null);

Function.apply is a shorter version of Function.prototype.apply.

Calling bind on it returns a special version of apply whose this is set to Math.max and when called, will have as it's first parameter (i.e. the value that would normally be used as this) set to null, since it's not going to be used.

So each element in arr will effectively be called using:

Math.max.apply(null, member);

The use of apply means the values in member are passed as parameters, as if:

Math.max(member[0],member[1] ... member[n]); 

So the expression returns the maximum value in each array. Those values are returned to map, which puts them into a new array.

var arr = [[1,2,3],[4,5,6]];
console.log(
  arr.map(Function.apply.bind(Math.max, null)) //[3, 6]
);

and is effectively the same as:

var arr = [[1, 2, 3],[4, 5, 6]];
console.log(
  arr.map(function(a) {return Math.max.apply(null, a)}) //[3, 6]
);

Though using recent features you might use destructing with rest parameter syntax:

var arr = [[1, 2, 3],[4, 5, 6]];
console.log(
  arr.map(a => Math.max(...a))   // [3, 6]
);