Sub topic 5
The Two Faces of +
This chapter assumes you already know how ToPrimitive, ToNumber, and ToString work. It also assumes you know that -, *, and / always convert their operands to numbers. The + operator is the exception. Depending on its operands, + either adds numbers or joins strings, and choosing between those two jobs happens at runtime.
The decision rule
When JavaScript evaluates a + b, it follows these steps:
- Convert both operands with ToPrimitive, using the "default" hint. Primitives stay as they are. Objects call
valueOfand thentoStringuntil one of them returns a primitive. - If either primitive is a string, convert both with ToString and concatenate them.
- Otherwise, convert both to numbers (or BigInts) and add them.
The string check happens after ToPrimitive. That ordering explains why objects and arrays usually end up concatenating: their toString returns a string.
Seeing the rule in action
console.log(1 + '2'); // '12' one string operand, so concatenation
console.log(true + 1); // 2 no strings, so true becomes 1
console.log(null + 1); // 1 null becomes 0
console.log(undefined + 1); // NaN undefined becomes NaN
console.log(true + '1'); // 'true1'
console.log([] + []); // '' both arrays become ''
console.log([] + {}); // '[object Object]'
console.log([1, 2] + [3]); // '1,23'None of the operands in the last three lines are strings at the start. ToPrimitive turns each array into a string, and from then on step 2 applies.
Left-to-right grouping
Binary + is left-associative, so a + b + c means (a + b) + c. Where the first string appears changes the result:
console.log(1 + 2 + '3'); // '33' (1 + 2) is 3, then 3 + '3'
console.log('1' + 2 + 3); // '123' ('1' + 2) is '12', then '12' + 3
console.log('1' + (2 + 3)); // '15' parentheses force the addition firstA common bug looks like 'Total: ' + price + tax. Once the left side is a string, every later + concatenates.
Dates prefer strings
Most objects try valueOf first under the default hint. Date is the exception: it treats the default hint as "string".
const d = new Date(0);
console.log(typeof (d + 1)); // 'string'
console.log(typeof (d - 1)); // 'number'Getting the behavior you intend
| Goal | Write | Avoid |
|---|---|---|
| Add values that may be strings | `Number(a) + Number(b)` | `a + b` |
| Build text | `` `Total: ${price + tax}` `` | `'Total: ' + price + tax` |
| Convert one value to a number | `+value` or `Number(value)` | `value * 1` (it works, but the intent is unclear) |
Exercise
What does [2] + 3 + 1 evaluate to, and why?
Show answer
It evaluates to '231'. ToPrimitive turns [2] into the string '2', so '2' + 3 gives '23', and then '23' + 1 gives '231'.
Exercise
Why does null + '1' give 'null1' while null + 1 gives 1?
Show answer
In the first expression one operand is a string, so null is converted with ToString to 'null' and the two are concatenated. In the second expression neither operand is a string, so null is converted to the number 0 and added to 1.