What is the toString method of the strings class in JavaScript?
In Javascript, we can use the toString method to get the string representation of an object.
Note: This function is equivalent to the
valueOf()method.
Syntax
toString();
Parameters
This function doesn’t need any parameters.
Return value
This function will return a string that represents a String object.
Note: every string in JavaScript is an object as well.
Code
var ourstring = new String("Hello, Educative!");let int1 = BigInt(234);console.log(ourstring, int1);console.log(ourstring.toString(), int1.toString());console.log("Hello, Educative!".toString()); // a string is also a string objectconsole.log("Hello, Educative!".toString() == ourstring.valueOf()); // these methods are equivalent
Explanation
- In lines 1 and 2, a
Stringobject with the value"Hello, Educative!"is created and aBigIntwith a value of234. - In lines 4 and 5, the difference is shown between printing
ourstringandint1as their respective objects and then their string representation, usingtoString(). - Line 7 shows how the result of using
toString()is equivalent to usingvalueOf().