valueOf And ToString Drive Object Coercion
Object coercion consults valueOf before toString: arithmetic gets the number, string contexts get the text, objects with neither become [object Object].
Code
// Objects convert through valueOf before toString; the operation's hint picks
// which one runs, and Symbol.toPrimitive (if defined) comes before both.
const price = {
valueOf() { return 42; },
toString() { return '42 dollars'; },
};
console.log(price + 8); // hint default/number: valueOf wins -> 50
console.log(`cost: ${price}`); // hint string: toString wins
console.log(price == 42); // loose equality converts the object to 42
console.log(String(price)); // explicit String(): always toString
console.log(Number(price)); // explicit Number(): valueOf
// Objects with neither hook fall through to the default toString
const plain = { tag: 'cpu' };
console.log(plain + '!'); // "[object Object]!" - the classic surpriseOutput
Captured from a sandboxed run of this snippet in the build pipeline.
50
cost: 42 dollars
true
42 dollars
42
[object Object]!What the demo hints
The price object defines valueOf returning 42 and toString returning 42 dollars. Arithmetic takes the numeric path: price + 8 prints 50 because the hint asks for a number and valueOf answers first.
String contexts flip the choice: the template literal prints cost: 42 dollars because toString serves string hints, while explicit String(price) and Number(price) pin the conversion decisively. Loose equality converts to 42, and the plain object without either hook falls back to [object Object] when concatenated.
Points worth noting
- Symbol.toPrimitive, if defined, outranks both hooks.
- The hint of the operation, number, string or default, picks the method.
Interactive Tools for This Topic
FAQ
- Which method does template-literal interpolation call?
- toString, because the string hint sends interpolation there; that is why the demo prints cost: 42 dollars while the addition prints 50.
Report a problem with this exampleOpens a pre-filled issue on GitHub.