Sub topic 5
The Two Faces of +
This chapter assumes you already know JavaScript's primitive types, can run code in a browser console or Node.js, and have read the earlier chapter on type coercion. That chapter introduced ToPrimitive, ToNumber, and ToString. Here we apply those conversions to the one arithmetic operator that does not always do arithmetic.
The + operator does two jobs. It adds numbers and it joins strings. Every other arithmetic operator (-, *, /, %, **) converts its operands to numbers. Only + has to decide which job to do first, and that decision explains most of the surprises people hit with it.
The Decision Algorithm for Binary +
When JavaScript evaluates a + b, it follows these steps from the specification:
- Evaluate the left operand, then the right operand.
- Convert both to primitives with ToPrimitive, using the hint
"default". - If either primitive is a string, convert both to strings with ToString and concatenate them.
- Otherwise, convert both to numeric values (Number or BigInt) and add them. If one is a BigInt and the other a Number, throw a
TypeError.
The order of these steps matters. The string check happens after ToPrimitive, so an object that turns into a string makes the whole expression a concatenation, even when the other operand is a number.
console.log(1 + '2'); // '12'
console.log(1 + 2); // 3
console.log(true + 1); // 2: true becomes 1
console.log(1 + null); // 1: null becomes 0
console.log(1 + undefined); // NaN: undefined becomes NaN
console.log('a' + null); // 'anull'
console.log('a' + undefined); // 'aundefined'
console.log([] + []); // '': each array becomes ''
console.log([] + {}); // '[object Object]'
console.log([1, 2] + [3]); // '1,23'Arrays and plain objects have no useful valueOf. Their valueOf returns the object itself, which is not a primitive, so ToPrimitive moves on to toString. An array's toString joins its elements with commas. A plain object's toString returns '[object Object]'. Once one side is a string, step 3 applies.
Left-to-Right Grouping Changes the Result
+ is left-associative, so a + b + c means (a + b) + c. Each step runs the algorithm again on its own pair of operands. Where the first string appears decides everything after it.
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 first
console.log(10 - '2' + '1'); // '81': 10 - '2' is 8, then 8 + '1'A common bug comes from building a message with a running total in the middle:
const items = 2;
const extra = 3;
console.log('Total: ' + items + extra); // 'Total: 23'
console.log('Total: ' + (items + extra)); // 'Total: 5'
console.log(`Total: ${items + extra}`); // 'Total: 5'Template literals avoid the problem because the expression inside ${} is evaluated on its own before it is inserted.
The "default" Hint and Why It Matters
Most operators ask ToPrimitive for a "number" hint, which tries valueOf before toString. Template literals and String() ask for a "string" hint, which tries toString first. Binary + passes "default". Ordinary objects treat "default" the same as "number". You can watch the hints with Symbol.toPrimitive:
const probe = {
[Symbol.toPrimitive](hint) {
console.log('hint:', hint);
return 1;
}
};
console.log(probe + 1); // hint: default, then 2
console.log(+probe); // hint: number, then 1
console.log(`${probe}`); // hint: string, then '1'This means the same object can give different results depending on how you combine it:
const price = {
valueOf() { return 10; },
toString() { return 'ten'; }
};
console.log(price + 1); // 11: default hint, valueOf runs first
console.log(price + ''); // '10': valueOf gives 10, then 10 becomes '10'
console.log(`${price}`); // 'ten': string hint, toString runs first
console.log(String(price)); // 'ten'The price + '' line catches people out. Adding an empty string is often used as a shortcut for converting to a string, but it does not call toString first. It calls valueOf, then converts that result to a string.
Date objects are the exception
Date defines its own Symbol.toPrimitive and treats "default" like "string". So + concatenates with dates, while - subtracts them.
const d = new Date(0);
console.log(typeof (d + 1)); // 'string': the date text followed by '1'
console.log(d - 0); // 0: milliseconds since the epoch
console.log(+d); // 0Unary +: Always a Number
Unary + (a + with only one operand) never concatenates. It applies ToNumber and returns the result. It does the same job as Number(x), with one difference: Number(1n) returns 1, while +1n throws a TypeError.
console.log(+'42'); // 42
console.log(+' 42 '); // 42: surrounding whitespace is ignored
console.log(+''); // 0
console.log(+'1e3'); // 1000
console.log(+'0x1F'); // 31
console.log(+'12px'); // NaN: the whole string must be numeric
console.log(+[]); // 0: [] becomes '', which becomes 0
console.log(+[7]); // 7
console.log(+[1, 2]); // NaN: '1,2' is not numeric
console.log(+null); // 0
console.log(+undefined); // NaN
console.log(+true); // 1| Input | `+x` / `Number(x)` | `parseInt(x, 10)` | `parseFloat(x)` |
|---|---|---|---|
| `'12px'` | `NaN` | `12` | `12` |
| `''` | `0` | `NaN` | `NaN` |
| `'3.7'` | `3.7` | `3` | `3.7` |
| `'0x1F'` | `31` | `0` | `0` |
| `null` | `0` | `NaN` | `NaN` |
Pick the conversion that matches your intent. Use + or Number when the whole string must be a number. Use parseInt or parseFloat when you want to read a leading number and ignore what follows. Note that an empty string becomes 0 under +, which can hide an empty form field.
Fixing the Classic Form-Input Bug
Values read from inputs, URL parameters, and localStorage are strings. Adding them with + concatenates.
const qty = '5'; // as read from an <input>
const bonus = '3';
console.log(qty + bonus); // '53'
console.log(Number(qty) + Number(bonus)); // 8
console.log(+qty + +bonus); // 8
function toNumberStrict(value) {
if (typeof value === 'string' && value.trim() === '') return NaN;
return Number(value);
}
console.log(toNumberStrict('') + 1); // NaN: the empty field is caught
console.log(toNumberStrict('4') + 1); // 5+= follows the same rules as +. So let total = '0'; total += 5; leaves total as '05'.
Values That Refuse to Join
Two kinds of values make + throw instead of guessing:
try {
'id:' + Symbol('x');
} catch (e) {
console.log(e instanceof TypeError); // true: symbols do not convert implicitly
}
console.log('id:' + String(Symbol('x'))); // 'id:Symbol(x)'
try {
1n + 1;
} catch (e) {
console.log(e instanceof TypeError); // true: BigInt and Number cannot be mixed
}
console.log('n=' + 1n); // 'n=1': concatenation with BigInt is allowedExercise
Predict each result: (a) 1 + 2 + '3' + 4 + 5, (b) [10] + 1, (c) +[10] + 1, (d) '3' - '1' + '1'.
Show answer
(a) '3345': 1 + 2 is 3, and every step after that concatenates. (b) '101': [10] becomes '10', so this is concatenation. (c) 11: unary + turns [10] into 10 first, then 10 + 1 is addition. (d) '21': '3' - '1' is the number 2, then 2 + '1' concatenates.
Exercise
An object is defined as const t = { valueOf() { return 5; }, toString() { return 'five'; } }. What do t + 1, t + '!', and ${t}! produce, and why do the last two differ?
Show answer
t + 1 is 6, and t + '!' is '5!'. Both use the default hint, so valueOf runs first. ${t}! is 'five!' because a template literal uses the string hint, which calls toString first.
Exercise
The code let sum = '0'; for (const v of ['2', '3']) sum += v; leaves sum as '023'. Rewrite it so that sum is the number 5, and explain the cause.
Show answer
Every operand is a string, so += concatenates. Start with a number and convert each value: let sum = 0; for (const v of ['2', '3']) sum += Number(v); This gives 5.