Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Math (parameter passing, arrays, and the "apply" method)

Tags:

javascript

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.");
like image 373
mjmitche Avatar asked Jul 27 '26 22:07

mjmitche


2 Answers

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

like image 95
Pointy Avatar answered Jul 31 '26 15:07

Pointy


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.

like image 41
Chris Jester-Young Avatar answered Jul 31 '26 15:07

Chris Jester-Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!