17

According to MDN Math.min accepts only numbers, and if one of the arguments is not a number, it'll return NaN. It's true that if we pass an array with multiple numbers we get NaN, like this: Math.min([1,2]), but if we use an array with just one number, Math.min will return the the number in the array, like in this example: Math.min([5]). Does anyone have an idea why we see this undocumented behavior?

47

According to MDN Math.min accepts only numbers, and if one of the arguments is not a number, it'll return NaN.

That's not what it says (bold emphasis mine):

If at least one of arguments cannot be converted to a number, the result is NaN.

Type Conversion:

  • Math.min uses ToNumber to convert its arguments.
  • ToNumber uses ToPrimitive to convert Objects (and Arrays are Objects).
  • ToPrimitive uses toString
  • [5].toString() is '5', which gets returned to ToPrimitive, which returns it to ToNumber, which parses it to 5 and returns it to Math.min, for which it is a valid argument, because it is not NaN.
  • [1, 2].toString(), OTOH, is '1, 2', which gets returned to ToPrimitive, which returns it to ToNumber, which parses it to NaN, because it is not a valid number representation. ToNumber then passes NaN to Math.min, which will then return NaN, because (as MDN states it) "one of its arguments cannot be converted to a number" or (as the spec states it) "If any value is NaN, the result is NaN.".
  • 25
    The ECMAScript spec is actually surprisingly readable, I just found out. – Jörg W Mittag Nov 5 '15 at 12:11
  • 3
    Yes. The Number([1,2]); results NaN but Number([1]) results 1. – Bhojendra Rauniyar Nov 6 '15 at 4:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.