JavaScript Object.prototype.toString() Method
Last Updated :
04 Jan, 2023
In JavaScript, the Object.prototype.toString() method is used to return a string that can represent the object. The toString() method is automatically inherited by every object which is inherited from Object. Whenever an object is represented as a text value or a string is expected from the object, the toString() method is called automatically.
Syntax:
obj.toString()
If one does not override the toString() method in case of custom objects, the toString() method returns the following:
[object type]
In the above syntax, the type denotes the object type.
Another use of the toString() method is that it can be used to convert base 10 numbers (and even bigInts) to other base numbers.
Syntax:
ExNum.toString(radix);
In the above syntax, the ExNum is an object of the object type number or bigInt and the radix refers to the base the number to is be converted to.
Example 1: The following example shows how the toString() method works when dealing with default object type and custom object type when the toString() method is not overridden.
JavaScript
function ExObjType(n) {
this .number = n;
}
function myFunction() {
const o = new String( 'Hello' );
console.log(o.toString());
const ExObj1 = new ExObjType(3);
console.log(ExObj1.toString());
}
myFunction();
|
Output:
Hello
[object Object]
Example 2: The following example shows how the toString() method works when dealing with custom object type and the toString() method is overridden :
JavaScript
function ExObjType(n) {
this .number = n;
}
ExObjType.prototype.toString = function ExObjToString() {
const ans = 'The number related to this object is '
+ this .number;
return ans;
}
function myFunction() {
const ExObj1 = new ExObjType(3);
console.log(ExObj1.toString());
}
myFunction();
|
Output:
The number related to this object is 3
Example 3: The following example shows how to use the toString() method to convert base 10 numbers to different base numbers.
JavaScript
function myFunction() {
const num1 = 12;
console.log(num1.toString(2));
console.log(num1.toString(8));
console.log(num1.toString(5));
}
myFunction();
|
Output:
1100
14
22
We have a complete list of Javascript Object methods, to check those please go through this Objects in JavaScript article.
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.