1) Why does the function smallest fail? I think it conforms to the example in the Mozilla documentation https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/min, which says
function getMin(x,y) { //from Mozilla documentation
return Math.min(x,y)
}
function smallest(array){ //my own experimentation with Resig`s example
return Math.min(array);
}
function largest(array){ //from John Resig`s learning advanced JavaScript #41
return Math.max.apply( Math, array );
}
assert(smallest([0, 1, 2, 3]) == 0, "Locate the smallest value.");
assert(largest([0, 1, 2, 3]) == 3, "Locate the largest value.");
The "Math.min()" function can take an arbitrary number of arguments. However, passing a single array to the function is just passing in one argument, not several. That single argument is the array itself. Arrays, you will recall, are first-rate values.
That's the whole point of the "apply" function that's available on every function. It is used to invoke the function and pass it an argument list composed of entries in an array instance. When you do this:
var array = [ 1, 2, 3, 4, 5 ];
someFunction.apply(irrelevant, array);
that's like calling:
someFunction(1, 2, 3, 4, 5);
(The "irrelevant" argument is what's to be used as the this value in the function call.)
Math.min and Math.max takes any number of numbers, as arguments. Your smallest is trying to pass an array, not numbers.
The use of apply (as in largest in your example) pastes the elements of the array as arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With