-2

How does

Math.max.apply(null, arr);

exactly work?

Suppose

var arr = [45,25,4,65] ;

will it compare 'null' and '45' and return maximum number between two adjacent e.g. 45?

After comparing will it again compare returned number and next array number e.g. 25 and return the max number?

And how is the calculation done internally? It is the same way, I think.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
varun teja-M.V.T
  • 104
  • 1
  • 10

2 Answers2

2

The first argument of apply is what will be this for the function. Here it does not matter as this function does not necessit a specific this value. It could matter in some other cases for instance:

var foo = {
    b: true,
    func: function() {
        return this.b;
    }
};
var bar = { b : false }; 

foo.func(); // true
foo.func.apply(bar); // false
Axnyff
  • 9,213
  • 4
  • 33
  • 37
0

It's equal to

 Math.max(...arr);

and that's equal to:

 Math.max(45, 25, 4, 65);

How it works internally is then up to the browsers / parsers native implementation. In js it might be:

 Math.max = (...args) => {
   let max = - Infinity;
   for(const number of args) 
      if(number > max) max = number;
   return max;
};
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151