Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  9] [ 5]  / answers: 1 / hits: 35049  / 14 Years ago, wed, may 19, 2010, 12:00:00

I was just digging through some JavaScript code (Raphaël.js) and came across the following line (translated slightly):



Math.min.apply(0, x)


where x is an array. Why on earth would you do this? The behavior seems to be take the min from the array x.


More From » javascript

 Answers
60

I realized the answer as I was posting my own question: This is the most succinct way of taking the min of an array x in JavaScript. The first argument is totally arbitrary; I find the 0 confusing because the code intuitively means Take the min of 0 and x, which is absolutely not the case. Using the Math object makes more sense for human-readability, but the Raphael.js authors are obsessed with minification and 0 is three bytes shorter.



See http://ejohn.org/blog/fast-javascript-maxmin/



For readability's sake, I'd strongly urge people to stop doing this and instead define a function along the lines of



function arrayMin(arr) { return Math.min.apply(Math, arr); };

[#96733] Monday, May 17, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hollievalerier

Total Points: 431
Total Questions: 93
Total Answers: 105

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
;