The Object.toString() method returns the given object as a string.
Example
toString() Syntax
The syntax of the toString() method is:
obj.toString()
Here, obj is the object that we want to convert to a string.
toString() Parameters
The toString() method does not take any parameters.
Note: The toString() method takes an optional parameter of number and bigInt types, which specifies the radix (numeric base) to be used for representing numeric values as strings.
toString() Return Value
The toString() method returns a string representing the object.
Example 1: JavaScript toString() With Built-in Objects
In the above example, the toString() method is used with built-in objects like number and Date.
The toString() method with the optional radix 2 converts the number into a string of binary numbers.
For the Date object, the toString() method returns the string representation of the date and time.
Example 2: toString() With Custom Object
In the above example, we have created a custom object dog1 with the help of the Dog() constructor function.
We get "[object Object]" as an output by default while accessing the toString() method on dog1 object.
However, we can override the default toString() method with our custom implementation.
Dog.prototype.toString = function dogToString() {
return `${this.name} is a ${this.sex} ${this.breed}.`;
};
As you can see, our custom toString() method returns a different string message instead of the default string value of "[object Object]".
Note: When used with objects, the toString() method returns the string "[object Object]" by default. However, it returns the primitive value for certain built-in objects like String, Number, Boolean, Array and Date.
Recommended Reading: