JavaScript Object Methods: toString, toLocaleString, valueOf and toJSON
The methods every object inherits from Object.prototype and the four you override: toString for readable strings, toLocaleString for locale-aware output, valueOf for numeric behavior, toJSON for serialization, plus type tags and Symbol.toStringTag.
kvi5hnuCode Sprout team member6 min readOn this page
Every ordinary object inherits a small set of methods from Object.prototype (article 46). Some, like hasOwnProperty, are utilities. Four of them exist mainly to be replaced: JavaScript calls them automatically at specific moments, and by defining your own versions you decide how your objects look as strings, compare as numbers and travel as JSON.
console.log(Object.getOwnPropertyNames(Object.prototype).sort().join(" "));
__defineGetter__ __defineSetter__ __lookupGetter__ __lookupSetter__ __proto__ constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf
The __double_underscore__ ones are legacy features kept for old code; modern equivalents are Object.getPrototypeOf, Object.defineProperty and Object.getOwnPropertyDescriptor (part 14). hasOwnProperty and propertyIsEnumerable were covered in article 48, and isPrototypeOf tests whether an object appears in another's prototype chain (part 9).
Here's when JavaScript calls each of the four overridable methods:

toString
toString() returns a string representation of the object. JavaScript calls it whenever it needs a string: String(obj), template literals, string concatenation (when there's no valueOf returning a primitive), array.join(), and as property keys.
The inherited version isn't helpful:
const point = { x: 1, y: 2 };
console.log(String(point), `${point}`);
[object Object] [object Object]
That [object Object] showing up in a web page or log message is the classic sign that an object was converted to a string by accident. Define your own:
const reading = {
celsius: 21.5,
toString() {
return `${this.celsius}°C`;
},
};
console.log(String(reading), `Now: ${reading}`, [reading, reading].join(" | "));
21.5°C Now: 21.5°C 21.5°C | 21.5°C
Built-in classes override it too: arrays join their elements with commas, functions return their source code, errors return "Name: message", dates return a readable date.
console.log(String([1, [2, 3]]));
console.log(String(function add(a, b) { return a + b; }));
console.log(String(new RangeError("too big")));
1,2,3
function add(a, b) { return a + b; }
RangeError: too big
Type tags: Object.prototype.toString
The original Object.prototype.toString, called directly on any value, returns a tag in the form "[object Type]". Before Array.isArray existed, this was the reliable way to detect types, and libraries still use it:
const tagOf = (value) => Object.prototype.toString.call(value);
console.log([null, [], new Date(0), /x/, () => 1, 1n, new Map(), Promise.resolve()].map(tagOf).join(" "));
[object Null] [object Array] [object Date] [object RegExp] [object Function] [object BigInt] [object Map] [object Promise]
Unlike typeof (article 9), it distinguishes null, arrays, dates and regular expressions. Your own classes report Object unless they define the well-known symbol Symbol.toStringTag (article 19):
class Temperature {
get [Symbol.toStringTag]() {
return "Temperature";
}
}
class Plain {}
console.log(Object.prototype.toString.call(new Temperature()), String(new Temperature()));
console.log(Object.prototype.toString.call(new Plain()));
[object Temperature] [object Temperature]
[object Object]
In new code, prefer specific checks: Array.isArray(v), v instanceof Date, typeof v === "function", Error.isError(v).
toLocaleString
toLocaleString() returns a string formatted for a locale: a language and region's conventions for numbers, dates and lists. The inherited version simply calls toString(). Numbers, dates, arrays and BigInts override it:
const total = 1234567.891;
console.log(total.toLocaleString("en-US"), total.toLocaleString("de-DE"));
console.log(total.toLocaleString("en-US", { style: "currency", currency: "USD" }));
1,234,567.891 1.234.567,891
$1,234,567.89
Give your own objects a toLocaleString when they contain numbers or dates that users will read, and pass the locale and options through:
const distance = {
meters: 12500.5,
toLocaleString(locale, options) {
return `${(this.meters / 1000).toLocaleString(locale, { maximumFractionDigits: 1, ...options })} km`;
},
};
console.log(distance.toLocaleString("en-US"), distance.toLocaleString("de-DE"));
console.log([distance, distance].toLocaleString("de-DE"));
12.5 km 12,5 km
12,5 km,12,5 km
Array.prototype.toLocaleString calls each element's toLocaleString with the same arguments. The full Intl API (Intl.NumberFormat, Intl.DateTimeFormat and friends) is covered in part 11. Output can differ slightly between runtimes and versions, because each one ships its own locale data, so don't compare locale-formatted strings in tests across environments.
valueOf
valueOf() is called when JavaScript needs a primitive, preferring a number: arithmetic, </> comparisons, unary + and, with the "default" hint, + and ==. The inherited version returns the object itself, which isn't a primitive, so JavaScript falls back to toString. Article 24 covers the full conversion algorithm and Symbol.toPrimitive.
Define valueOf when your object has a natural numeric value:
const distance = { meters: 1500, valueOf() { return this.meters; } };
console.log(distance + 500, distance > 1000, distance * 2);
const start = new Date(Date.UTC(2026, 0, 1));
const end = new Date(Date.UTC(2026, 0, 2));
console.log(end - start, start < end); // Date.valueOf gives milliseconds
2000 true 3000
86400000 true
Dates are the main built-in example: their valueOf returns the timestamp, which is why you can subtract and compare them.
When an object has both, which one wins depends on the operation:
const answer = { valueOf() { return 42; }, toString() { return "forty-two"; } };
console.log(answer + "", `${answer}`, String(answer), answer * 2);
42 forty-two forty-two 84
+ uses the default hint, so valueOf wins; templates and String() use the string hint, so toString wins. This surprise is one reason to use valueOf sparingly: define it only when numeric behavior is obviously right, and give the object a separate, explicit method like toMeters() otherwise.
toJSON
Object.prototype has no toJSON, but JSON.stringify looks for one on every value it serializes and, if present, serializes its result instead (article 50). Date defines it to produce ISO strings:
const money = {
cents: 1999,
currency: "EUR",
toString() { return `${(this.cents / 100).toFixed(2)} ${this.currency}`; },
toJSON() { return this.toString(); },
};
console.log(JSON.stringify({ price: money }), JSON.stringify(new Date(0)));
{"price":"19.99 EUR"} "1970-01-01T00:00:00.000Z"
Put methods on the prototype
These examples define methods on individual objects to keep things short. In real code, you'd define toString and friends once, in a class (part 9), so every instance shares them through the prototype.
Common questions
Why does my object show [object Object] in the page?
It was converted to a string with the default toString, typically by string concatenation, a template literal or setting textContent. Pick the property you meant (user.name), use JSON.stringify(obj) for debugging, or define a toString.
Should I use toString or String(x)?
String(x) works for every value, including null and undefined, while x.toString() throws for those. Both call your custom toString on objects.
Is toString called for object keys?
Yes: map[obj] = 1 converts obj to a string key using toString (or Symbol.toPrimitive). Objects with the default toString all become "[object Object]", which is why a Map is better for object keys (article 47).
What's the difference between Object.prototype.toString.call(x) and x.toString()?
The first always runs the original method, giving the "[object Type]" tag. The second runs whatever toString the value has, which for arrays, dates, functions and your own objects is an override.
Summary
- Objects inherit
toString,toLocaleString,valueOf,hasOwnProperty,isPrototypeOf,propertyIsEnumerableand a few legacy methods fromObject.prototype. toStringis used for string conversion; override it to avoid[object Object].console.logdoesn't use it.Object.prototype.toString.call(v)returns a type tag like"[object Array]"; classes can customize it withSymbol.toStringTag.toLocaleString(locale, options)formats for a locale; arrays call it on each element.valueOfprovides a primitive for arithmetic and comparisons; the+operator and templates can disagree when both methods exist.toJSONlets an object choose howJSON.stringifyrepresents it.
Practice Questions
What does this print?
const t = { toString() { return "T"; } };
console.log(t + "!", [t, t].join(""));
Answer
T! TT. Neither operation finds a valueOf that returns a primitive (the inherited one returns the object), so both fall back to toString.
What does this print?
const v = { valueOf: () => 10 };
console.log(v + 5, `${v}`);
Answer
15 [object Object]. + with a number uses valueOf; the template literal asks for a string, and the inherited toString gives [object Object].
Write a Point-like object literal whose string form is (3, 4) and whose JSON form is [3,4].
Answer
const p = { x: 3, y: 4, toString() { return `(${this.x}, ${this.y})`; }, toJSON() { return [this.x, this.y]; } };
Then String(p) gives "(3, 4)" and JSON.stringify(p) gives "[3,4]".
How can you tell an array from a plain object without Array.isArray?
Answer
Object.prototype.toString.call(value) === "[object Array]". typeof gives "object" for both.
Previous: JSON in JavaScript: JSON.stringify and JSON.parse, Replacers, Revivers and Pitfalls
Next: JavaScript Object Literal Syntax: Shorthand Properties, Computed Keys, Methods and Spread

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.