Javascript – Why does Math.min work with a one element array

javascriptmath

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?

Best Answer

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