toString() on an object
The toString() method is JavaScript's built-in way
to convert an object into a string (string representation).
This method is called automatically,
when an object needs to be used in a text context -
for example, during concatenation (+), logging, template strings, and so on.
Short version
Syntax:
obj.toString()Returns the string representation of the object.
Example - basic behavior
const user = { name: 'Alice' };
console.log(user.toString()); // "[object Object]"By default toString() is inherited from Object.prototype,
and returns a string of the form:
"[object ObjectType]"When it is called automatically
const user = { name: 'Alice' };
console.log('User: ' + user);
// "User: [object Object]"
alert(user);
// "[object Object]"JS automatically calls toString()
to turn the object into a string.
You can override toString()
You can set your own string representation of the object:
const user = {
name: 'Alice',
age: 25,
toString() {
return `${this.name} (${this.age})`;
}
};
console.log(String(user)); // "Alice (25)"
console.log('User: ' + user); // "User: Alice (25)"During + concatenation or String(obj) -
the overridden toString() is called.
Comparison with valueOf()
When JS tries to convert an object to a primitive, it calls, in priority order:
obj[Symbol.toPrimitive](if present)obj.toString()(if a string is expected)obj.valueOf()(if a number is expected)
Example:
const user = {
name: 'Alice',
valueOf() {
return 42;
},
toString() {
return 'User';
}
};
console.log(String(user)); // "User"
console.log(Number(user)); // 42Different built-in objects have their own toString()
| Type | Example | Result |
|---|---|---|
Object | {} | [object Object] |
Array | [1, 2, 3].toString() | "1,2,3" |
Date | (new Date()).toString() | "Tue Oct 14 2025 17:00:00 GMT+0300 (...)" |
Function | (() => {}).toString() | "() => {}" |
RegExp | /abc/.toString() | "/abc/" |
Map, Set | [object Map], [object Set] | not revealed |
Advanced example - formatting JSON
If you want a string with the object's contents,
not just [object Object],
use JSON.stringify():
const user = { name: 'Alice', age: 25 };
console.log(user.toString()); // "[object Object]"
console.log(JSON.stringify(user)); // '{"name":"Alice","age":25}'JSON.stringify() is not toString(),
it is a separate JSON serialization mechanism.
SUMMARY
| What it does | Converts an object into a string |
|---|---|
| Where it's defined | Object.prototype.toString |
| By default | Returns "[object Object]" |
| Can be overridden | Yes |
| Called automatically | during concatenation, String(), logs, template strings |
| Alternative | JSON.stringify(obj) - for full contents |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.