toString

Returns a string representing the specified object.

Applies to

Function

Syntax

toString()

Parameters

None

Description

Every object has a toString method that is automatically called when it is to be represented as a text value or when an object is referred to in a string concatenation.

You can use toString within your own code to convert an object into a string, and you can create your own function to be called in place of the default toString method.

For Function objects, the built-in toString method decompiles the function back into the JavaScript source that defines the function This string includes the function keyword, the argument list, curly braces, and function body.

For example, assume you have the following code that defines the Dog object type and creates theDog, an object of type Dog:

function Dog(name,breed,color,sex) {
      this.name=name
      this.breed=breed
      this.color=color
      this.sex=sex
}
theDog = new Dog("Gabby","Lab","chocolate","girl")

Any time Dog is used in a string context, JavaScript automatically calls the toString function, which returns the following string:

function Dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; }

For information on defining your own toString method, see the Object: toString method.