Friday 5 January 2018

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

This happens because [] is
coerced to 0.


You can see this
with the following call:


(new
Number([])).valueOf(); //
0

Therefore, calling
Math.min([]) is the same as calling
Math.min(0) which gives
0.




I
believe that the reason that new Number([]) treats
[] as 0 is
because:



  1. The href="http://www.ecma-international.org/ecma-262/6.0/#sec-number-constructor-number-value"
    rel="nofollow noreferrer">spec for the Number(value)
    constructor uses a ToNumber
    function.

  2. The href="http://www.ecma-international.org/ecma-262/6.0/#sec-tonumber" rel="nofollow
    noreferrer">spec for the ToNumber(value) function
    says to use ToPrimitive for an object
    type (which an array is).

  3. The primitive value of an array
    is equal to having the array joined, e.g. [] becomes
    "", [0] becomes
    "0" and [0, 1] becomes
    "0,1".

  4. The number constructor
    therefore converts [] into "" which is
    then parsed as
    0.


The
above behaviour is the reason that an array with one or two numbers inside it can be
passed into Math.min(...), but an array of more
cannot:



  • Math.min([])
    is equal to Math.min("") or
    Math.min(0)

  • Math.min([1])
    is equal to Math.min("1") or
    Math.min(1)

  • Math.min([1,
    2])
    is equal to Math.min("1,2") which cannot be
    converted to a number.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...