toString()  Object  instance method JS Home  <<  JS Reference  <<  Object  <<  toString()


Returns a string of the specified object.

  • Automatically invoked when an object is called and a string is expected or when viewing the object as a string.
  • The Object.toString() method is inherited by all Object descendants.
  • Unless overridden by a custom object toString() returns [object Object].


Signature Description
anObject.toString()Returns a string of the specified object.




The code below creates an object and displays it.

// Create an object.
anObject = new Object();

alert(anObject.toString() + ' anObject is an Object instance.');

Press the button below to action the above code:

Overriding The Object.toString() Method

As you can see when pressing the above button the default for toString() on an objectType of Object returns [object Object]. If you want something meaningful returned for your object, you need to override the Object.toString() method.

The code below creates a custom object type function and overrides the Object.toString() method. We then create and display a string of the object which will use our custom toString() method.

// Define a custom object type function.
function HomeOwner(firstName,lastName) {  

// Define a custom override function for toString().
HomeOwner.prototype.toString = function HomeOwnerToString() {  
  var owns = this.firstName + ' ' + this.lastName + ' owns a house!';  
  return owns;  

// Create and print a HomeOwner object.
owner = new HomeOwner('Barney','Magrew');  


Press the button below to action the above code:

Related Tutorials

JavaScript Basic Tutorials - Lesson 7 - Objects