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?
Javascript – Why does Math.min work with a one element array
javascriptmath
Best Answer
That's not what it says (bold emphasis mine):
Type Conversion:
Math.min
usesToNumber
to convert its arguments.ToNumber
usesToPrimitive
to convertObject
s (andArray
s areObject
s).ToPrimitive
usestoString
[5].toString()
is'5'
, which gets returned toToPrimitive
, which returns it toToNumber
, which parses it to5
and returns it toMath.min
, for which it is a valid argument, because it is notNaN
.[1, 2].toString()
, OTOH, is'1, 2'
, which gets returned toToPrimitive
, which returns it toToNumber
, which parses it toNaN
, because it is not a valid number representation.ToNumber
then passesNaN
toMath.min
, which will then returnNaN
, 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.".