Skip to main content

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:

javascript
obj.toString()

Returns the string representation of the object.


Example - basic behavior

javascript
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:

javascript
"[object ObjectType]"

When it is called automatically

javascript
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:

javascript
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:

  1. obj[Symbol.toPrimitive] (if present)
  2. obj.toString() (if a string is expected)
  3. obj.valueOf() (if a number is expected)

Example:

javascript
const user = { name: 'Alice', valueOf() { return 42; }, toString() { return 'User'; } }; console.log(String(user)); // "User" console.log(Number(user)); // 42

Different built-in objects have their own toString()

TypeExampleResult
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():

javascript
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 doesConverts an object into a string
Where it's definedObject.prototype.toString
By defaultReturns "[object Object]"
Can be overriddenYes
Called automaticallyduring concatenation, String(), logs, template strings
AlternativeJSON.stringify(obj) - for full contents

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.