The answer linked from the comment posted by hardik-shah would certainly give you a better understanding of how these type of evaluations get handled in javascript. That answer points to the ecma docs, which is also useful. I'll try and give a limited explanation of how the examples you posted work.
Below I've quoted the article I used as the basis to interpreting how these instances of the +
operator work. I believe I've interpreted the article correctly, but I'm no expert on these things so I would be happy to be corrected.
[] + [] === ''; // true
This is true because both operands are objects; [].valueOf
doesn't return a primitive, so [].toString
is used, which evaluates to ''
[] * 1 === 0; // true
This is true because, as one of the operands is a primitive, arithmetic is used rather than concatenation. '' * 1
evaluates to 0 * 1
, which equals 0
false + 1 === 1; // true
Both operands here are primitives, so arithmetic will be used. Number(false)
gives us 0, so 0 + 1
equals 1
From this article
- If at least one operand is an object, it is converted to a primitive value (string, number or boolean)
- After conversion, if at least one operand is string type, the second operand is converted to string and the concatenation is executed
- In other case both operands are converted to numbers and arithmetic addition is executed.
The object to primitive conversion:
- If object type is Date, then toString() method is used;
In other case
valueOf() method is used, if it returns a primitive value;
In other case (if valueOf() doesn't exist or doesn't return a primitive value),
then toString() method is used. This happens most of the times.