Saturday 1 April 2017

javascript - Why does Math.min([]) evaluate to 0?





Why does Math.min([]) evaluate to 0?



I would expect that it would evaluate to NaN since MDN's manpage for Math.min states "If at least one of the arguments cannot be converted to a number, NaN is returned."



So I guess the refined question is why does [] coerce to 0? Especially considering that [] is truthy (i.e. !![] === true) and Math.min(true) === 1. I am thinking about this wrong?




Tested on Node v7.0.0


Answer




Why does Math.min([]) evaluate to 0?




Because the spec says so:



Math.min casts each parameter to a number using...




ToNumber casts objects to a number using...



ToPrimitive casts objects to primitive values using...



[[Default Value]] internal method converts objects to primitives based on their hint parameter.



The default hint for all objects is string. Which means the array gets converted to a string, which for [] is "".



ToNumber then converts "" to 0, per the documented algorithm




Math.min then takes the only parameter and returns it, per its algorithm.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...