Why does an empty array plus false return the string "false"?
> [] + false
> "false"
An empty array is false, right?
Then false + false = false? No?
Short answer: because the spec says so.
Longer answer: When the left operand of the +
operator is not a string or a number, the operand will be converted to either one of those depending on their "preferred" primitive type (defined in the spec). The array's "preferred" type is a string and [].toString()
is an empty string.
Then, still according to the spec, because the left operand is a string (following the previous conversion), the right operand will be converted to a string and the result of the +
operation will be the concatenation of both strings.
In other words, [] + false
is equivalent to [].toString() + false.toString()
(or "" + "false"
) and results in the string "false"
.
Other interesting results as a consequence of this:
[1,2,3] + false // "1,2,3false"
[1,[2]] + false // "1,2false"
[] + {} // "[object Object]"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With