Name

Object.toString() — define an object’s string representation

Synopsis

object.toString()

Returns

A string representing the object.

Description

The toString() method is not one you often call explicitly in your JavaScript programs. Instead, you define this method in your objects, and the system calls it whenever it needs to convert your object to a string.

The JavaScript system invokes the toString() method to convert an object to a string whenever the object is used in a string context. For example, an object is converted to a string when it is passed to a function that expects a string argument:

alert(my_object);

Similarly, objects are converted to strings when they are concatenated to strings with the + operator:

var msg = 'My object is: ' + my_object;

The toString() method is invoked without arguments and should return a string. To be useful, the string you return should be based, in some way, on the value of the object for which the method was invoked.

When you define a custom class in JavaScript, it is good practice to define a toString() method for the class. If you do not, the object inherits the default toString() method from the Object class. This default method returns a string of the form:

[objectclass]

where class is the class of the object: a value such as “Object”, “String”, “Number”, “Function”, “Window”, “Document”, and so on. This behavior of the default toString() method is occasionally useful to determine the type or class of an unknown object. Because most objects have ...

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.