How does the Math.max.apply() work?
apply
accepts an array and it applies the array as parameters to the actual function. So,
Math.max.apply(Math, list);
can be understood as,
Math.max("12", "23", "100", "34", "56", "9", "233");
So, apply
is a convenient way to pass an array of data as parameters to a function. Remember
console.log(Math.max(list)); # NaN
will not work, because max
doesn't accept an array as input.
There is another advantage, of using apply
, you can choose your own context. 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
.
console.log(Math.max.apply(undefined, list)); # 233console.log(Math.max.apply(null, list)); # 233console.log(Math.max.apply(Math, list)); # 233
Since apply
is actually defined in Function.prototype
, any valid JavaScript function object, will have apply
function, by default.
On JavaScript ES6 just use the Spread operator:
var list = ["12","23","100","34","56","9","233"];console.log(Math.max(...list));// ^^^ Spread operator
Can anyone tell me how does the below code work?
Math.max.apply(Math,list)
Invokes a Math.max
function with Math
object to be used as a this
reference in the function implementation (body) and list
to be passed as an arguments.
So this eventually equals to
Math.max("12","23","100","34","56", "9","233")
It seems it works if i pass null or Math.
Obviously Math.max
implementation doesn't use instance variable - there is no reason to do so. The native implementation would just iterate over arguments
and find the maximum one.
Does all the user-defined/Native functions have call and apply method which we can use?.
Yes, every single function can be invoked using call
or apply
References:
- MDN
.apply()
documentation (credits to @RGraham)