-1

I came across with a question about apply when using it with e.g. Math.max. For example let's say I have an array:

var arr = [1, 2, 3, 4, 5];
var biggest = Math.max.apply(Math, arr);
console.log(biggest);//outputs 5 which is correct

But whatever value I passed as first argument I always get the same result:

var biggest = Math.max.apply(this, arr);
var biggest = Math.max.apply(null, arr);
var biggest = Math.max.apply("", arr);
var biggest = Math.max.apply(window, arr);
...

console.log(biggest);//all above output 5 why??

The only assumption I can make is that the Math.max when is been called throw apply the function context doesn't matter in this situation?

user2019037
  • 764
  • 1
  • 7
  • 14

3 Answers3

1

Why would it matter what this is if you're finding the max value in an array you're passing in?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
1

The first parameter you pass to apply of any function, will be the this inside that function. But, max doesn't depend on the current context. So, anything would work in-place of Math.

shruti1810
  • 3,920
  • 2
  • 16
  • 28
0

max would be is static method on a class language like Java. It doesn't relay on the context it just uses the parameters. You can see that when you call it you don't create an instance of Math, just access its methods. This is call functional programming as there no state that could affect the result. The output of a function will be always the same as long as the inputs are the same

Raulucco
  • 3,406
  • 1
  • 21
  • 27