Sub topic 13
Coercion in + and Other Arithmetic Operators
This chapter assumes you already know the earlier conversion rules: ToNumber, ToString, and ToPrimitive with its "default", "number", and "string" hints. Here you apply them to operators. The + operator is the one that needs care, because it does two jobs: numeric addition and string concatenation. Every other arithmetic operator does one job and always works with numbers.
The two jobs of +
Binary + (the form with two operands) makes its choice only after both operands are primitives. The specification's steps, in order, are:
- Evaluate the left operand, then the right operand.
- Convert each to a primitive with ToPrimitive and the
"default"hint, left first. - If either primitive is a string, convert both with ToString and concatenate them.
- Otherwise, convert both with ToNumeric, which yields a Number or a BigInt.
- If one is a BigInt and the other a Number, throw a
TypeError. Otherwise, add.
Step 3 checks types after the ToPrimitive step, not before. An array is not a string, but it becomes one during ToPrimitive, so the array then makes + concatenate.
The + rules show up in these results:
console.log(1 + "2"); // "12": a string operand forces concatenation
console.log("3" + 4 + 5); // "345": ("3" + 4) is "34", then "34" + 5
console.log(3 + 4 + "5"); // "75": (3 + 4) is 7, then 7 + "5"
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(null + "x"); // "nullx": the string wins, null becomes "null"
console.log([] + []); // "": each [] becomes ""
console.log([1, 2] + [3]); // "1,23": "1,2" + "3"
console.log([] + {}); // "[object Object]"
console.log(1n + 2n); // 3nLeft-to-right grouping
+ groups from left to right, so a + b + c means (a + b) + c. A string anywhere in a chain affects only the operations after it. In 3 + 4 + "5", the two numbers are added before the string appears. This explains a common bug in string-building code:
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"A template literal keeps the arithmetic and the text apart, which removes the ambiguity.
Other arithmetic operators always mean numbers
The operators -, *, /, %, and ** have no string mode. Each one calls ToNumeric on both operands. ToNumeric runs ToPrimitive with the "number" hint, so for ordinary objects valueOf is tried before toString.
console.log("3" - 1); // 2
console.log("3" * "4"); // 12
console.log("10" / "4"); // 2.5
console.log("7" % 2); // 1
console.log("2" ** "3"); // 8
console.log("5" - - "2"); // 7: unary - turns "2" into -2
console.log("abc" - 1); // NaN: "abc" becomes NaN
console.log([5] * 2); // 10: [5] becomes "5", then 5
console.log({} * 2); // NaN
console.log(" 12 " - 2); // 10: whitespace is trimmed
console.log("" - 1); // -1: the empty string becomes 0These operators accept any operand and never complain about strings, so a bad string input produces NaN and no error. NaN then spreads through every later calculation.
Unary + and unary -
Unary +x applies ToNumber, so people use it as a short way to convert to a number. Unary -x applies ToNumeric and negates. The two differ on BigInt:
console.log(+"42"); // 42
console.log(+""); // 0
console.log(+[]); // 0
console.log(-"5"); // -5
console.log(-1n); // -1n: unary minus supports BigInt
try {
console.log(+1n);
} catch (e) {
console.log(e.name); // "TypeError": unary + never accepts BigInt
}Unary + throws on BigInt on purpose. asm.js code relied on +x always producing a Number, and allowing BigInt would have broken that.
The increment and decrement operators ++ and -- also use ToNumeric. If let s = "5", then after s++ the variable s holds the number 6, not the string "51".
Hints matter: the Date exception
Binary + uses the "default" hint, and other operators use "number". For most objects the two hints behave the same, because ordinary objects treat "default" like "number". Date objects are the built-in exception. A Date treats "default" like "string":
const d = new Date(0);
console.log(typeof (d + 1)); // "string": a date string followed by "1"
console.log(d - 0); // 0: the number hint gives the timestamp
console.log(typeof +d); // "number"To do arithmetic on a date, call d.getTime() or use -. Don't rely on +.
Failure modes
| Expression | Result | Cause |
|---|---|---|
| `1n + 1` | `TypeError` | BigInt and Number cannot be mixed in arithmetic |
| `+1n` | `TypeError` | Unary + only produces Numbers |
| `1 + Symbol()` | `TypeError` | Symbols refuse implicit number conversion |
| `"" + Symbol()` | `TypeError` | Symbols refuse implicit string conversion |
| `"a" - 1` | `NaN` | No error, so the bad value spreads silently |
| `{} + []` typed at statement start | `0` in some consoles | `{}` is parsed as an empty block, leaving `+[]` |
The last row comes from the parser and has nothing to do with coercion. As an expression, ({} + []) evaluates to "[object Object]".
The BigInt rule exists because no implicit conversion is safe in both directions. Converting a large BigInt to a Number loses precision, and converting 1.5 to a BigInt is impossible. So the language makes you choose:
const big = 10n;
const n = 3;
console.log(big + BigInt(n)); // 13n
console.log(Number(big) + n); // 13Comparison operators such as 1n < 2 do allow mixing. That is covered in the chapter on relational comparisons.
Tracing a custom object
Objects that define Symbol.toPrimitive show which hint each operator sends:
const probe = {
[Symbol.toPrimitive](hint) {
console.log("hint:", hint);
return hint === "number" ? 100 : "probe";
}
};
console.log(probe + 1); // hint: default, then "probe1"
console.log(probe - 1); // hint: number, then 99
console.log(probe * 2); // hint: number, then 200
console.log(`${probe}`); // hint: string, then "probe"Exercise
Predict each result: "4" + 2 - 1, "4" - 2 + 1, and [2] * [3] + "".
Show answer
"4" + 2 - 1 is 41: "4" + 2 gives "42", then "42" - 1 gives 41. "4" - 2 + 1 is 3: "4" - 2 gives 2, then 2 + 1 gives 3. [2] [3] + "" is "6": each array becomes a string and then a number, so 2 3 is 6, and 6 + "" gives "6".
Exercise
A form field gives you qty = "3". The code total = qty + 1 produces "31". Give two fixes, and explain why qty - -1 is a poor fix even though it returns 4.
Show answer
Use Number(qty) + 1, or parse with parseInt(qty, 10) + 1. Either one makes the conversion visible. qty - -1 does work, because - forces a numeric conversion, but it hides the intent, and readers cannot easily tell it was written to avoid concatenation.
Exercise
Why does new Date(0) + 1 return a string while new Date(0) - 1 returns -1?
Show answer
Binary + calls ToPrimitive with the "default" hint, and Date treats "default" as "string", so the date becomes a date string and + concatenates. Binary - calls ToPrimitive with the "number" hint, which returns the timestamp 0, so the result is 0 - 1, which is -1.