Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an empty array plus false in JS return a string?

Tags:

javascript

Why does an empty array plus false return the string "false"?

> [] + false

> "false"

An empty array is false, right?

Then false + false = false? No?

like image 800
OPV Avatar asked Oct 19 '19 17:10

OPV


1 Answers

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]"
like image 193
dee-see Avatar answered Oct 23 '22 13:10

dee-see