Skip to content
jshacks.dev
Fundamentals

How JavaScript Converts Objects to Primitive Values

An object becomes a primitive through Symbol.toPrimitive, valueOf and toString, in an order set by a hint. See each hint and how to take control of it.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, npm and Vite logos.

Objects reach operators all the time: you add a date to a number, interpolate an array into a message, compare two money objects with >. The operator needs a primitive, so the engine converts the object, and the way it does so explains outputs like [object Object], 1,2 and a date that turns into a long string when you wanted a timestamp. The procedure is one algorithm with three inputs. This post walks through it, shows how to take control of it with Symbol.toPrimitive, and covers the failure when it cannot produce a primitive. Examples run on Node.js 24. It is the missing middle step in how type coercion works, and it is the reason [] == false is true in the post on loose equality.

The hint

The engine passes a hint saying which primitive the caller prefers. The hint is "string" when the operator wants text, "number" when it wants a number, and "default" when it has no preference.

OperationHint
Template literal, String(obj), property key"string"
-, *, /, <, >, unary +, Number(obj)"number"
+, ==, !="default"

The hint then sets the order of two methods. For "string", the engine calls toString() first and valueOf() second. For "number" and "default", the order is reversed. The first one that returns a primitive supplies the result.

JavaScript
const order = {
  valueOf() {
    console.log("valueOf");
    return 42;
  },
  toString() {
    console.log("toString");
    return "order-42";
  },
};

console.log(`${order}`);
console.log(order * 2);
console.log(order + 1);
console.log(order + "");
Text
toString
order-42
valueOf
84
valueOf
43
valueOf
42

The template literal asked for a string and got toString(). Multiplication asked for a number and got valueOf(). And order + 1 and order + "" both used the default hint, which prefers valueOf(), so the string concatenation at the end printed 42 and not order-42. That last result surprises people: adding an empty string does not call toString() when valueOf() returns a primitive.

What the built-ins return

Plain objects and arrays inherit valueOf() and toString() from Object.prototype and Array.prototype. The default valueOf() returns the object itself, which is not a primitive, so the conversion falls through to toString().

JavaScript
console.log({}.valueOf() === {}.valueOf());
console.log(String({}));
console.log(String([1, 2, 3]));
console.log(String([[1, 2], [3]]));
console.log(String(() => 1));
console.log([] + []);
console.log([] + {});
Text
false
[object Object]
1,2,3
1,2,3
() => 1

[object Object]

The first line is a quiet check that valueOf() returns the object, and since each {} is a new object, comparing two returns false. Plain objects stringify to [object Object], arrays to a comma-joined list, and functions to their source text. This is why interpolating an array or an object into a message gives unhelpful text: it takes the default path. The [] + [] line prints an empty string. For anything meant to be read, use JSON.stringify() for data or a formatter that you control.

Date is the exception that catches people. It overrides the default hint, treating it as "string".

JavaScript
const date = new Date(86400000);

console.log(typeof (date + 1));
console.log(typeof (date - 1));
console.log(date - new Date(0));
console.log(date > new Date(0));
Text
string
number
86400000
true

Adding a number to a date concatenates, because the default hint becomes a string. Subtracting converts to numbers and gives milliseconds. This is why date2 - date1 is the idiom for a duration and date + 1 is almost always a mistake. The post on date pitfalls covers more of them.

Taking control with Symbol.toPrimitive

A method stored under the well-known symbol Symbol.toPrimitive overrides both valueOf() and toString(). It receives the hint and returns a primitive, so one object can behave differently per context.

JavaScript
class Money {
  constructor(cents) {
    this.cents = cents;
  }

  [Symbol.toPrimitive](hint) {
    if (hint === "string") return `$${(this.cents / 100).toFixed(2)}`;
    return this.cents;
  }
}

const price = new Money(1250);

console.log(`${price}`);
console.log(price + 50);
console.log(price * 2);
console.log(price > 1000);
console.log(price == 1250);
Text
$12.50
1300
2500
true
true

The template used the "string" branch and printed a formatted price. Everything else used the numeric branch, so addition, multiplication and both comparisons work on cents. That one method replaced two, and the hint makes the intent explicit. We write it that way for value classes where arithmetic or ordering makes sense, with the caveat that arithmetic on money in cents is the interesting part and the conversion is only the surface.

Logging the hint is the fastest way to learn which one an operator uses.

JavaScript
const seen = [];
const probe = {
  [Symbol.toPrimitive](hint) {
    seen.push(hint);
    return 1;
  },
};

`${probe}`;
probe + 1;
probe * 1;
probe > 0;
probe == 1;
[probe].join();

console.log(seen);
Text
[ 'string', 'default', 'number', 'number', 'default', 'string' ]

Template literals ask for a string, + and == use the default, * and > ask for a number, and join() converts its items to strings.

When no primitive comes back

If Symbol.toPrimitive is missing and both valueOf() and toString() return objects, or are missing, the engine gives up with a TypeError.

JavaScript
const bare = Object.create(null);

try {
  console.log(bare + "");
} catch (error) {
  console.log(error.name);
  console.log(error.message);
}

const dictionary = Object.create(null);
dictionary.hello = "world";
console.log(JSON.stringify(dictionary));
Text
TypeError
Cannot convert object to primitive value
{"hello":"world"}

An object created with Object.create(null) has no toString() or valueOf(), so it cannot be converted implicitly, which surprises people who use such objects as dictionaries and then interpolate them into an error message. JSON.stringify() works on them because it does not use this algorithm.

Comparing and sorting custom values

A class with a numeric conversion sorts and compares without extra code, which makes Symbol.toPrimitive or valueOf() useful for value objects such as versions, durations and money.

JavaScript
class Duration {
  constructor(seconds) {
    this.seconds = seconds;
  }

  valueOf() {
    return this.seconds;
  }

  toString() {
    return `${this.seconds}s`;
  }
}

const times = [new Duration(90), new Duration(5), new Duration(30)];

console.log(times.sort((a, b) => a - b).map(String));
console.log(new Duration(5) < new Duration(30));
console.log(`${new Duration(5)}`);
console.log(new Duration(5) + new Duration(30));
Text
[ '5s', '30s', '90s' ]
true
5s
35

The comparator a - b works because subtraction asks for numbers and gets valueOf(). The template literal asks for a string and gets toString(). Adding two durations uses the default hint, which prefers valueOf(), and returns the number 35, not a Duration, which is a sign that arithmetic operators are a poor way to build value types. A plus() method that returns a new Duration is better design, and keeping valueOf() for comparison only is a sensible compromise.

Practical consequences

Three habits follow from this. Never rely on implicit conversion of objects in output meant for people; format explicitly. When you define a class that will be compared or summed, implement Symbol.toPrimitive and test each hint. And when a log line shows [object Object], the cause is the string path with no override, and the fix is JSON.stringify(value) or a custom toString().

Equality is a separate matter: the objects { id: 1 } and { id: 1 } convert to the same string and are still unequal, because == between two objects compares identity and never calls the conversion. The algorithm only runs when an object meets a primitive. The post on equality for objects and arrays covers comparing content.

Debugging an unexpected conversion

When an object prints wrongly or an operator returns a surprising number, ask three questions. Which hint did the operator use, which you can read from the table above? Does the object have Symbol.toPrimitive, a custom valueOf() or a custom toString(), which you can check with Object.getOwnPropertyNames on the object and its prototype chain? And does the first method in the order return a primitive? A valueOf() that returns this falls through to toString() silently, which is why most plain objects stringify.

A quick way to see the order is to define both methods with a log line, as in the first example, and run the expression. Ten seconds of experiment beats reading the spec for the case you have.

Where this does not apply

Operators on two objects, such as a < b, still convert both to primitives, so comparing dates or custom value classes works through the same path. But === never converts, and Object.is never converts, so none of this matters for identity checks.

If your project uses TypeScript, the compiler rejects arithmetic on object types, so these paths are reached mostly through dynamic data and any. Reading old code that relies on valueOf() for sorting or arithmetic is where the knowledge pays off.

The algorithm is defined in the specification as ToPrimitive, and MDN covers the symbol on its Symbol.toPrimitive reference page.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.