The Object.toString()
method returns the given object as a string.
Example
// create a number with value 10
let num = 10;
// check the type of num before
// using the toString() method
console.log(typeof num);
// Output: number
// check the type of num after
//using the toString() method
console.log(typeof num.toString());
// Output: string
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
// create a number with value 10
let num = 10;
// toString() method of number object takes in
// optional radix argument (numeral base)
console.log(num.toString(2));
// Output: "1010"
//create a new date object
let date = new Date();
console.log(date.toString());
// Output: Thu Aug 06 2020 12:08:44 GMT+0545 (Nepal Time)
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
// constructor function to create a new object
function Dog(name, breed, sex) {
this.name = name;
this.breed = breed;
this.sex = sex;
}
// create a new object
let dog1 = new Dog("Daniel", "bulldog", "male");
console.log(dog1.toString());
// Output: [object Object]
// override the default toString() in the custom object
Dog.prototype.toString = function dogToString() {
return `${this.name} is a ${this.sex} ${this.breed}.`;
};
console.log(dog1.toString());
// Output: Daniel is a male bulldog.
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
.
Also Read: