Friday, July 26, 2019

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...