CodePark/ questions / Types & coercion
START PRACTICINGPRACTICE
Frontend question · JavaScript › Types & coercion

What does this log?

console.log([] + {}, "5" - 2, "5" + 2, true + 1);
[object Object] 3 52 2

The + operator first turns objects into primitive values (simple values like strings and numbers). If either side is then a string, + joins the two as strings.
•
[] becomes '' and {} becomes '[object Object]', so [] + {} is '[object Object]'.
•
'5' + 2 joins strings and gives '52'.
• The
- operator only works on numbers, so '5' - 2 turns '5' into 5 and gives 3.
•
true + 1 turns true into 1 and gives 2.

The tempting option "0 3 7 2" is wrong because
+ with a string joins text. It does not add numbers.