tags:

views:

95

answers:

1

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."

+6  A: 

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); };
Trevor Burnham
It's worth noting that the "0" in the Raphael code represents the scope that Math.min is executed with. The reason this "should" be Math is because that's the native/natural scope for that method when normally invoked. Using zero presumably is equivalent to null there, which is equivalent to the global object (window). This works fine assuming that the method doesn't need access to internal state of the Math object, which is probably a safe assumption, but is still an assumption. Don't use that pattern yourself if you can help it. As you (Trevor) note, use Math there.
quixoto
Correction to the above: Using zero here is not equivalent to null. It is semantically goofy, and results in the scope being a Number object representing zero, which is basically worthless. This keeps character count to a minimum, but still makes an assumption about the inner workings of "min".
quixoto
Minification? Is that really a word? :)
GregS
@Greg: http://en.wikipedia.org/wiki/Minification_(programming)
quixoto
@GregS, it used to be called using-various-and-sundries-coding-techniques-and-automatic-code-processing-tools-to-reduce-the-file-that-will-be-sent-to-the-client-to-the-smallest-reasonably-achievable-size. Then it was called uvasctaacpttrtftwbsttcttsras for short. The pronunciation of the acronym naturally morphed into the word minification.
jball
Thanks quixoto, and thanks for the laugh jball. I am now smarter, I think.
GregS