What is Object.toString() in Javascript?

The Object.toString() method returns a string that represents an object. We can also use this to change the base of numbers from decimal to other bases.

  • The toString() method is automatically invoked when the string value of the object is expected.

  • The method is inherited by the descendants of the object.

  • The objects override the method to return a specific string value. In case the toString() method is not overridden, [object type] is returned.

Declaration

The toString() method is declared as follows:

obj.toString()
  • obj: The object that is to be represented as string.

The base of numbers is converted from decimal to other bases as follows:

num.toString(base)
  • num: The number in base 10 that is converted to other bases.
  • base: The base in which num is converted.

Overriding the toString() method

The toString() method of a custom object is overridden as follows:

obj.prototype.toString =function() 
{ 
    return str; 
};
  • obj: The object that is to be represented as string.
  • str: The string representation of obj.

Return value

The toString() method returns the string representation of obj.

Browser compatibility

The toString() method is supported by the following browsers:

Codes

Code 1

Consider the code snippet below, which demonstrates the use of toString() method:

var Student = { Name: 'Ali', RollNo: '234' }
//toString() method not overridden
console.log(Student.toString())
var Student = "Ali"
//toString() method overridden of String
console.log(Student.toString())

Code 2

Consider another example in which toString() method of a custom class is overridden:

//Custom object
function Student(Name,id) {
this.Name = Name;
this.id = id;
}
//Overriding valueOf() method
Student.prototype.toString = function ()
{
return 'Hello! i am '+this.Name;
}
// calling valueOf() method
Student1 = new Student('Ali',2);
console.log(Student1.toString());

Example 3

The toString() method is used to convert numbers from base 10 to other bases as follows:

var num = 10
console.log("num = ", num)
console.log("num in base 2 = ", num.toString(2))
console.log("num in base 16 = ", num.toString(16))
console.log("num in base 8 = ", num.toString(8))
Copyright ©2024 Educative, Inc. All rights reserved