Search code examples
javascripttype-conversionloose-typing

In JavaScript, why is +[1.5] considered numeric?


I've been doing JavaScript a long time, but just noticed something I've never seen before. Consider:

> +[1.5]
1.5

Why does this happen? Is this a special rule to interpret arrays as numerical or is it an accident of spec alchemy?

Note also that:

> +[1,0]
NaN

This makes sense to me, of course, but I would have expected that +[1] is also NaN because, well, it's not a number. Or is it somehow classified as a number?

Then there are these cases, which lead me to believe we're traveling through a type coercion wormhole (array ==> string, string ==> number):

> [2] + [4]
"24"
> + [2] + [4]
"24"
> (+[2]) + (+[4])
6
> +[2] + [4,5]
"24,5"
> // which, incidentally, looks like a european-formatted number, but I see
> // that that's just an accident (still another possibility for confusion)

Is any of this intentional?


Solution

  • The Unary + operator internally uses the ToNumber abstract operation.

    So the unary operator when applies to an object it applies toString() (abstract operation ToPrimitive) first and then applies ToNumber abstract operation, So basically + when applied to array of single number it converts it to the number itself.

    If it is applied to [4,5] then toString will return 4,5 which inturn when applied a ToNumber abstract operation returns NaN.

    // Trying to concatenate two string as [] coerce to strings = 24
    [2] + [4]
    // Converting 2 and 4 to number and then adding = 6   
    (+[2]) + (+[4])
    // Converting 2 to number and 4,5 will be coerced to string = 24,5
    +[2] + [4,5]