Sub topic 3
How JavaScript Converts Types Behind the Scenes
This chapter assumes you can declare variables, know the primitive types (string, number, boolean, null, undefined, symbol, bigint), and can run code in a console or Node.js.
Many operators expect a specific type. When they get something else, JavaScript converts the value for you. The specification defines this conversion as a small set of internal operations: ToPrimitive, ToNumber, ToString, and ToBoolean. You can't call them directly, but every coercion you see is built from them. Once you know them, operator results become predictable.
ToPrimitive: Turning Objects into Primitives
Operators work on primitives. When an operand is an object, JavaScript first calls ToPrimitive with a hint that says which type it would prefer:
| Hint | When it is used | Order of methods tried |
|---|---|---|
| `"number"` | Math operators such as `*`, `-`, `<` | `valueOf()`, then `toString()` |
| `"string"` | Template literals, `String(x)` | `toString()`, then `valueOf()` |
| `"default"` | `+`, `==` | Same as `"number"` (except `Date`, which uses string order) |
JavaScript uses the first method that returns a primitive. If an object defines Symbol.toPrimitive, that method runs instead and receives the hint.
const price = {
valueOf() { return 42; },
toString() { return 'price'; }
};
console.log(price * 2); // 84: number hint, valueOf wins
console.log(`${price}`); // 'price': string hint, toString wins
console.log(price + ''); // '42': default hint behaves like number
const temp = {
[Symbol.toPrimitive](hint) {
return hint === 'number' ? 21 : `hint was ${hint}`;
}
};
console.log(+temp); // 21
console.log(`${temp}`); // 'hint was string'
console.log(temp + ''); // 'hint was default'Plain objects and arrays don't override valueOf (it returns the object itself, which is not a primitive), so in practice they fall through to toString().
ToNumber and ToString
After ToPrimitive, the result usually goes through ToNumber or ToString.
console.log(Number('')); // 0: empty string becomes 0
console.log(Number(' 12 ')); // 12: whitespace is trimmed
console.log(Number('12px')); // NaN: any invalid character fails
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
console.log(Number(true)); // 1
console.log(Number([])); // 0: [] -> '' -> 0
console.log(Number([5])); // 5: [5] -> '5' -> 5
console.log(Number({})); // NaN: {} -> '[object Object]' -> NaN
console.log(String(null)); // 'null'
console.log(String([1, [2, 3]])); // '1,2,3'
console.log(String({})); // '[object Object]'
console.log(String(-0)); // '0': the sign is lostToBoolean
ToBoolean never calls ToPrimitive. It looks the value up in a fixed list: a short set of values become false, and every object, including [] and {}, becomes true. The chapter on truthy and falsy values covers that list.
Common Mistakes
- Assuming
Number()andparseInt()behave the same.parseInt('12px')is12, butNumber('12px')isNaN. - Expecting an empty array to convert to
falseorNaN. As a number it becomes0, and as a boolean it becomestrue. - Forgetting that a custom
valueOfchanges how your objects behave with every math operator.
Exercise
What does Number([' 7 ']) return, and which conversion steps produce it?
Show answer
It returns 7. ToPrimitive calls the array's toString, which gives ' 7 '. ToNumber then trims the whitespace and parses 7.
Exercise
An object has valueOf() { return {}; } and toString() { return '3'; }. What is obj * 2?
Show answer
6. The number hint tries valueOf first, but it returns an object, which is not a primitive. JavaScript then calls toString, gets '3', converts it to 3, and multiplies by 2.