It works like that because that’s how it’s specified to work.
EcmaScript standard specifies that unless either of the arguments is a string, the +
operator is assumed to mean numeric addition and not string concatenation. Conversion to numeric values is explicitly mentioned:
Return the result of applying the addition operation to ToNumber( lprim) and ToNumber(rprim).
(where lprim
and rprim
are the primitive forms of the left-hand and the right-hand argument, respectively)
EcmaScript also specifies the To Number
conversion for booleans clearly:
The result is 1 if the argument is true. The result is +0 if the argument is false.
Hence, true + true
effectively means 1 + 1
, or 2
.