Sub topic 3
How JavaScript Converts Types Behind the Scenes
This chapter assumes you know the primitive types (string, number, bigint, boolean, undefined, null, symbol), how objects differ from primitives, and how to run code in Node.js or a browser console. You have already seen what operators and operands are. This chapter covers what happens when an operator receives an operand of a type it does not expect.
Most JavaScript operators work on primitives. When you pass them something else, the engine runs a small set of internal routines that the specification calls abstract operations. You cannot call them directly, but every operator that coerces uses them. If you learn these four, the later chapters on +, ==, and < become predictable:
- ToPrimitive turns an object into a primitive.
- ToNumber turns a value into a number.
- ToString turns a value into a string.
- ToBoolean turns a value into
trueorfalse.
ToPrimitive: Getting a Primitive Out of an Object
ToPrimitive does nothing to a value that is already a primitive. For an object, it takes a hint that says what the caller would like back: "number", "string", or "default".
- Arithmetic such as
*,-, and unary+passes"number". - Template literals and
String(obj)pass"string". - Binary
+and==pass"default".
The algorithm has two stages:
- If the object has a
Symbol.toPrimitivemethod, call it with the hint. If it returns a primitive, use that. If it returns an object, throw aTypeError. - Otherwise, run the ordinary fallback. With hint
"string", trytoString()and thenvalueOf(). With"number"or"default", tryvalueOf()and thentoString(). The first primitive result wins. If neither method returns a primitive, throw aTypeError.
You can watch the order by logging from each method:
const price = {
valueOf() { console.log('valueOf called'); return 42; },
toString() { console.log('toString called'); return 'forty-two'; },
};
console.log(price * 2); // valueOf called, then 84
console.log(`${price}`); // toString called, then 'forty-two'
console.log(price + ''); // valueOf called, then '42' (default hint acts like number)Plain objects inherit valueOf() from Object.prototype, and it returns the object itself. Because that result is not a primitive, the fallback moves on to toString(). This is why ({}) * 1 ends up as '[object Object]' and then NaN, and why an array turns into its comma-joined contents.
Taking control with Symbol.toPrimitive
const temperature = {
[Symbol.toPrimitive](hint) {
console.log('hint:', hint);
if (hint === 'number') return 21;
if (hint === 'string') return '21°C';
return 'default-21';
},
};
console.log(+temperature); // hint: number -> 21
console.log(String(temperature)); // hint: string -> '21°C'
console.log(temperature + 1); // hint: default -> 'default-211'Date is the built-in exception. Its Symbol.toPrimitive treats "default" as "string", so + concatenates dates while - subtracts them:
const d = new Date(0);
console.log(typeof (d + 1)); // 'string'
console.log(d - 0); // 0 (milliseconds since the epoch)When ToPrimitive fails
const broken = {
valueOf() { return {}; },
toString() { return {}; },
};
try {
broken * 1;
} catch (e) {
console.log(e instanceof TypeError); // true
}
const bare = Object.create(null); // no inherited valueOf or toString
try {
`${bare}`;
} catch (e) {
console.log(e instanceof TypeError); // true
}ToNumber: The Numeric Conversion
ToNumber is what -, *, /, %, unary +, and Number(value) use. (Arithmetic operators actually call a close relative, ToNumeric, which lets a BigInt through unchanged. A later chapter covers that case.)
| Input | Result |
|---|---|
| `undefined` | `NaN` |
| `null` | `0` |
| `true` / `false` | `1` / `0` |
| `''` or `' '` | `0` |
| `' 42 '` | `42` (whitespace is trimmed) |
| `'0x1A'`, `'0b101'`, `'1e3'` | `26`, `5`, `1000` |
| `'12px'` | `NaN` (the whole string must be numeric) |
| Symbol | `TypeError` |
| Object | ToPrimitive with hint `"number"`, then ToNumber |
console.log(Number(null), Number(undefined)); // 0 NaN
console.log(Number('\n 7 \t')); // 7
console.log(Number([]), Number([5]), Number([1, 2])); // 0 5 NaN
console.log(Number('12px'), parseInt('12px', 10)); // NaN 12
console.log(Number(''), parseInt('', 10)); // 0 NaNThe arrays follow the ToPrimitive path: [] becomes '', which becomes 0. [5] becomes '5'. [1, 2] becomes '1,2', which is not a number.
ToString: The String Conversion
ToString runs inside template literals, String(value), and the concatenation branch of +.
| Input | Result |
|---|---|
| `undefined`, `null` | `'undefined'`, `'null'` |
| `true` | `'true'` |
| `-0` | `'0'` (the sign is lost) |
| `1e21` | `'1e+21'` |
| `10n` | `'10'` (no `n` suffix) |
| `[1, [2, 3]]` | `'1,2,3'` |
| `[null, undefined]` | `','` (null and undefined become empty) |
| `{}` | `'[object Object]'` |
| Symbol | `TypeError` when implicit |
const sym = Symbol('id');
console.log(String(sym)); // 'Symbol(id)': explicit conversion is allowed
try {
`${sym}`;
} catch (e) {
console.log(e instanceof TypeError); // true: implicit conversion is not
}
console.log(String(-0), `${[null, undefined, 3]}`); // '0' ',,3'String(x) handles symbols as a special case. Implicit conversion, and even sym + '', throws.
ToBoolean: The Simplest One
ToBoolean never calls methods and never throws. It checks the value against a fixed list of falsy values, and anything not on the list, including every object, becomes true. if, !, &&, ||, and Boolean(value) all use it. The Truthy and Falsy Values chapter covers the full list. For now, note that ToBoolean skips ToPrimitive entirely:
const zeroBox = { valueOf() { return 0; } };
console.log(Boolean(zeroBox)); // true: valueOf is never consulted
console.log(zeroBox * 1); // 0: ToNumber does consult itExplicit Versus Implicit Conversion
Explicit conversion with Number(), String(), or Boolean() runs the same abstract operations as implicit conversion. The only differences are the Symbol and BigInt special cases above. The difference that matters in practice is readability. Number(input) states what you intend. input * 1 makes the reader work out which conversion happens.
| You want | Explicit | Implicit equivalent |
|---|---|---|
| Number | `Number(x)` | `+x`, `x - 0` |
| String | `String(x)` | `` `${x}` ``, `x + ''` (not identical for symbols, or for objects with a custom default hint) |
| Boolean | `Boolean(x)` | `!!x` |
Common Errors
- Assuming
valueOfalways wins. It wins only for the"number"and"default"hints. Template literals calltoStringfirst. - Expecting dates to add numerically.
date + 1000concatenates. Usedate.getTime() + 1000. - Treating empty strings as invalid numbers.
Number('')andNumber(' ')are0, so an empty form field can pass a!isNaN(Number(x))check. - Returning an object from
toStringorSymbol.toPrimitive. The conversion throws instead of falling back.
Exercise
Given const box = { valueOf() { return 10; }, toString() { return '7'; } }; what do box * 2, ${box}, and box + '1' evaluate to, and why?
Show answer
box * 2 is 20, because the number hint calls valueOf first. ${box} is '7', because the string hint calls toString first. box + '1' is '101', because binary + uses the default hint, which calls valueOf and gets 10. Since the other operand is a string, 10 is then converted to '10' and concatenated with '1'.
Exercise
Explain step by step why Number([' 8 ']) is 8 but Number([8, 9]) is NaN.
Show answer
Both arrays go through ToPrimitive with hint "number". valueOf returns the array itself, which is not a primitive, so toString runs and calls join. [' 8 '] becomes ' 8 ', and ToNumber trims the whitespace to get 8. [8, 9] becomes '8,9', which is not a valid numeric string, so the result is NaN.
Exercise
Write an object money such that +money is 5, ${money} is '$5.00', and money + 1 is 6.
Show answer
const money = { [Symbol.toPrimitive](hint) { return hint === 'string' ? '$5.00' : 5; } }; The number and default hints both return 5, so +money is 5 and money + 1 is 6. The string hint returns '$5.00'.