Object-to-Primitive Conversion in JavaScript: valueOf, toString and Symbol.toPrimitive
What happens when an object meets +, ==, < or a template literal: the three hints (string, number, default), the valueOf/toString order, how arrays, dates and plain objects convert, writing your own conversions with Symbol.toPrimitive, and when custom conversions are a bad idea.
kvi5hnuCode Sprout team member6 min readOn this page
Articles 22 and 23 kept saying "the object is converted to a primitive first". This article explains exactly how. It's the last piece of JavaScript's conversion rules, and it answers questions such as: why is [] + [] an empty string? Why does new Date() - 0 give a number while new Date() + 0 gives text? And how can your own classes behave sensibly in ${...} or with <?
Objects to booleans: always true
The easy case first. Converting any object to a boolean doesn't call any method: every object is truthy, including [], {} and new Boolean(false) (article 17).
The three hints
Converting to a string or number is harder, because an object might have several reasonable primitive forms. A date, for example, can be a readable string or a millisecond timestamp. So the operation that needs a primitive passes a hint saying what it would prefer:
| Hint | Used by | Typical result |
|---|---|---|
"string" | `${obj}`, String(obj), using obj as a property key, array.join() | text |
"number" | unary +obj, -, *, /, %, Number(obj), Math functions, <, >, <=, >= | a number |
"default" | binary +, == and != | for most objects, same as "number" |
The "default" hint exists because + and == work with both strings and numbers, so they genuinely have no preference.
The algorithm

- If the object has a
[Symbol.toPrimitive]method, call it with the hint. It must return a primitive, or aTypeErroris thrown. - Otherwise, use the "ordinary" algorithm:
- hint
"string": calltoString(); if it doesn't return a primitive, tryvalueOf(); - hint
"number"or"default": callvalueOf(); if it doesn't return a primitive, trytoString().
- hint
- If neither method returns a primitive, throw a
TypeError.
Then the resulting primitive is converted further if needed. For example, Number(obj) turns a string result into a number.
Plain objects, arrays and functions
Every object inherits valueOf() and toString() from Object.prototype. The inherited valueOf() returns the object itself, which isn't a primitive, so in practice toString() decides:
console.log(String({}), String({ a: 1 })); // Object.prototype.toString
console.log(String([1, [2, [3]]])); // arrays join their elements
console.log(String([null, undefined, 1])); // null and undefined become ""
console.log(String(/a+/g), String(new Error("boom")));
console.log(String(function greet() { return "hi"; })); // the source text
console.log(Number([]), Number([7]), Number(["7"]), Number([1, 2]), Number({}));
[object Object] [object Object]
1,2,3
,,1
/a+/g Error: boom
function greet() { return "hi"; }
0 7 7 NaN NaN
This explains the conversion-table surprises from article 22. Number([]): valueOf returns the array (not primitive), toString returns "", and Number("") is 0. Number([7]): the array's string is "7", which becomes 7. Number([1, 2]): "1,2" isn't a number, giving NaN.
Dates: the exception
Date objects have their own [Symbol.toPrimitive] method, which treats the "default" hint as "string". That's why + concatenates dates while - subtracts them:
const epoch = new Date(0);
console.log(typeof (epoch + 1), typeof (epoch - 1)); // default → string; number → number
console.log(epoch - 1, +epoch);
console.log(new Date(5) > new Date(1)); // < and > use numbers: comparisons work
console.log(new Date(5).getTime() - new Date(1).getTime()); // the explicit, clearer way
string number
-1 0
true
4
So you can compare dates with < and > and subtract them to get milliseconds. But == and === compare date objects by identity: new Date(0) == new Date(0) is false. Compare getTime() values instead. Part 11 covers dates (and their modern replacement, Temporal) in detail.
Custom conversions with valueOf and toString
Your own classes can define valueOf() and toString(). A common, reasonable use is toString() for a readable representation:
class Money {
constructor(cents) { this.cents = cents; }
valueOf() { return this.cents; } // number-like contexts
toString() { return "$" + (this.cents / 100).toFixed(2); } // string contexts
}
const coffee = new Money(150), cake = new Money(275);
console.log(`${coffee}`, String(cake)); // hint "string": toString
console.log(coffee < cake, cake - coffee); // hint "number": valueOf
console.log(coffee + cake); // hint "default": valueOf, so 425, not text!
console.log(coffee + ""); // also "default": "150", not "$1.50"
$1.50 $2.75
true 125
425
150
The last two lines show the trap: binary + uses the "default" hint, which goes to valueOf() first. So coffee + "" gives "150", not "$1.50", while a template literal gives "$1.50". Mixing the two styles in one codebase produces inconsistent output.
Symbol.toPrimitive: full control
[Symbol.toPrimitive](hint) receives the hint directly and can decide anything. Logging the hint shows exactly which operations ask for what:
const probe = {
[Symbol.toPrimitive](hint) {
console.log("hint:", hint);
return hint === "number" ? 1 : "text";
},
};
`${probe}`; // string
+probe; // number
probe * 2; // number
probe < 5; // number
probe + 1; // default
probe == "text"; // default
const key = { [probe]: true }; // string (property key)
hint: string
hint: number
hint: number
hint: number
hint: default
hint: default
hint: string
A sensible implementation for a temperature class:
class Temperature {
constructor(celsius) { this.celsius = celsius; }
[Symbol.toPrimitive](hint) {
if (hint === "number") return this.celsius;
return `${this.celsius}°C`; // "string" and "default"
}
}
const today = new Temperature(23);
console.log(`Now: ${today}`);
console.log(today > 20, today * 1.8 + 32);
console.log("Reading: " + today); // default → the string form
Now: 23°C
true 73.4
Reading: 23°C
When conversions fail
If every attempt returns an object, there's nothing left to try:
const stubborn = { valueOf() { return {}; }, toString() { return {}; } };
try {
stubborn + 1;
} catch (err) {
console.log(err.name);
}
const bare = Object.create(null); // no prototype: no valueOf or toString at all
try {
`${bare}`;
} catch (err) {
console.log(err.name);
}
TypeError
TypeError
The second case appears in real code: objects created with Object.create(null) (often used as dictionaries) have no toString, so interpolating or concatenating them throws TypeError: Cannot convert object to primitive value.
Should you define custom conversions?
Some guidelines:
toString()for debugging and display is usually fine. It makes logs and string templates readable.- Be careful with
valueOf(). It makes objects silently participate in arithmetic and comparisons, where explicit methods (a.cents + b.cents,a.compareTo(b)) are often clearer and safer. It also interacts confusingly with+, as shown above. Symbol.toPrimitiveis the most predictable if you do want conversions, because one method handles all hints in one place.- Note what doesn't use these hooks:
JSON.stringifycallstoJSON()if present, nottoString; andconsole.login browsers and Node.js inspects the object's properties rather than converting it.
Common questions
Why is [] + {} "[object Object]"?
Binary + converts both operands with the "default" hint. [] becomes "" (valueOf returns the array, so toString's "" is used), and {} becomes "[object Object]". Since one result is a string, + concatenates: "" + "[object Object]".
Does == call valueOf?
When comparing an object with a primitive, yes: it uses the "default" hint, which means valueOf() first for ordinary objects (and the string form for dates). When both operands are objects, == compares identity and calls nothing.
What does toString return for an object of my class?
"[object Object]", unless you override it or define a Symbol.toStringTag getter (which changes it to "[object YourTag]", article 19).
Is String(obj) always the same as obj.toString()?
No. String(obj) goes through Symbol.toPrimitive first if it exists, and also works for null, undefined and symbols. obj.toString() calls that one method directly and throws for null and undefined.
Summary
- Objects are always truthy. For strings and numbers, they're converted via
ToPrimitivewith a hint:"string","number"or"default". [Symbol.toPrimitive](hint)wins if present. Otherwise "string" triestoStringthenvalueOf; "number" and "default" tryvalueOfthentoString.- Plain objects, arrays and functions effectively use
toString("[object Object]", joined elements, source text). - Dates treat "default" as "string", so
date + 1concatenates whiledate - 1and<use the timestamp. - Custom
valueOfmakes+and==behave numerically; prefertoStringfor display andSymbol.toPrimitivefor full control, or explicit methods.
Practice Questions
What does [1, 2] + [3] evaluate to?
Answer
"1,23". Both arrays become strings ("1,2" and "3"), and + concatenates.
An object has valueOf() { return 42 } and toString() { return "x" }. What are obj + 1, `${obj}` and obj * 2?
Answer
43, "x" and 84. + uses the default hint (valueOf first), the template uses the string hint (toString first), and * uses the number hint.
Why is new Date(0) + 1 a long string but new Date(0) - 1 equal to -1?
Answer
Date's Symbol.toPrimitive treats the "default" hint (used by +) as "string", giving the date text plus "1". - uses the "number" hint, giving the timestamp 0, minus 1.
What does Number([" 12 "]) return?
Answer
12. The array's string form is " 12 ", and Number trims whitespace before parsing.
Write a [Symbol.toPrimitive] method for a Percent class that holds value = 0.25, so that ${p} gives "25%" and p * 100 gives 25.
Answer
[Symbol.toPrimitive](hint) {
return hint === "number" ? this.value : `${Math.round(this.value * 100)}%`;
}
The number hint returns 0.25 (so p * 100 is 25), and the string and default hints return the formatted text.
Previous: Implicit Type Coercion and == in JavaScript: The Rules Behind the Surprises
Next: Declaring Variables in JavaScript: let, const and Naming

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.