Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the Math.max.apply() work?

How does the Math.max.apply() work?.

<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>JS Bin</title> </head> <body>   <script>       var list = ["12","23","100","34","56",                                     "9","233"];       console.log(Math.max.apply(Math,list));       </script> </body> </html> 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

The above code finds the Max number in the List. Can anyone tell me how does the below code work?. It seems it works if i pass null or Math.

console.log(Math.max.apply(Math,list)); 

Does all the user-defined/Native functions have call and apply method which we can use?.

like image 243
Shane Avatar asked Jan 21 '14 10:01

Shane


People also ask

How does math MAX work in JS?

max() The Math. max() function returns the largest of the zero or more numbers given as input parameters, or NaN if any parameter isn't a number and can't be converted into one.

What is the difference between math MIN () and math MAX () functions?

when you execute Math. min(), you will get (Infinity) and when you execute Math. max(), you will get (-Infinity). by this result for sure if you compare Math.

What does math max method return?

max(int a, int b) returns the greater of two int values. That is, the result is the argument closer to positive infinity. If the arguments have the same value, the result is that same value.

Why is math Max negative Infinity?

max is returning -Infinity when there is no argument passed. If no arguments are given, the result is -∞. So when you spread an empty array in a function call, it is like calling the function without an argument. But the result is negative infinity, not positive.


1 Answers

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));   # 233 console.log(Math.max.apply(null, list));        # 233 console.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.

like image 178
thefourtheye Avatar answered Sep 25 '22 05:09

thefourtheye