AppDividend
Latest Code Tutorials

Javascript Object toString Example | Object toString() Method Tutorial

0

Javascript Object toString Example | Object toString() Method Tutorial is today’s topic. The Object​.prototype​.toString() method returns a string representing the object. Every object has the toString() method that is automatically called when an object is to be represented as the text value or when an object is referred to in a manner in which a string is expected.

Javascript Object toString Example

By default, Javascript Object toString() method is inherited by every object descended from the Object. If this method is not overridden in the custom object, toString() returns “[object type],” where type is an object type. The syntax is following.

object.toString()

It returns the string representing the object.

See the following example.
// app.js

function GoT(name) {
  this.name = name
}

let name = new GoT('Jon Snow')

console.log(name.toString())

The output is following.

Javascript Object toString Example

 

Overriding the default toString() method

You can create the function to be called in place of the default toString() method. Javascript Object toString() method takes no arguments and should return the string. Object toString method you create can be any value you want, but it will be the most useful if it carries information about an object. See the following example.

// app.js

function GoT(name) {
  this.name = name
}

let name = new GoT('Jon Snow')

GoT.prototype.toString = function() { 
  return ''+this.name;
}

console.log(name.toString())

The output is following.

 

Object toString() Method Tutorial

Finally, Javascript Object toString Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.