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 whichnumis 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 ofobj.
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 overriddenconsole.log(Student.toString())var Student = "Ali"//toString() method overridden of Stringconsole.log(Student.toString())
Code 2
Consider another example in which toString() method of a custom class is overridden:
//Custom objectfunction Student(Name,id) {this.Name = Name;this.id = id;}//Overriding valueOf() methodStudent.prototype.toString = function (){return 'Hello! i am '+this.Name;}// calling valueOf() methodStudent1 = 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 = 10console.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))
Free Resources