Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does empty array convert to string? [duplicate]

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 391
OPV Avatar asked Dec 31 '25 00:12

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 97
dee-see Avatar answered Jan 01 '26 19:01

dee-see