What does this type-coercion snippet print, and why?
What does the following code print, and why?
console.log(1 + 2 + '3');
console.log('3' * 2);
console.log('5' - 1);
console.log([] + {});
Predict the output and explain.
Lines print '33', 6, 4, and '[object Object]'. + evaluates left to right: (1 + 2) is 3, then 3 + '3' concatenates to '33' because one operand is a string. * and - force numbers, so '3' * 2 is 6 and '5' - 1 is 4. In [] + {}, [] stringifies to '' and {} to '[object Object]', joining to '[object Object]'.
- ✗Thinking
+always sums — with any string operand it concatenates - ✗Assuming
-and*concatenate like+does on strings - ✗Expecting
{}to stringify to'{}'rather than'[object Object]'
- →Why does
+evaluate strictly left to right in1 + 2 + '3'? - →Why does
[] + {}give'[object Object]'rather than an error?
Solution
The key is the behavior of + with a string (concatenation) versus * and - (numeric coercion).
console.log(1 + 2 + '3'); // '33'
console.log('3' * 2); // 6
console.log('5' - 1); // 4
console.log([] + {}); // '[object Object]'
How it works
+ evaluates left to right. In 1 + 2 + '3', first 1 + 2 = 3 (both numbers), then 3 + '3' has one string operand, so it concatenates into '33'.
The * and - operators are defined only for numbers, so strings are coerced to numbers: '3' * 2 is 6 and '5' - 1 is 4.
In [] + {}, both operands are coerced to a primitive via their string form: [] gives '' and {} gives '[object Object]', so '' + '[object Object]' yields '[object Object]'. </content>