I'm trying to understand why you would ever use toString() on a string.
tutorialspoint gives this example.
<html>
<head>
<title>JavaScript String toString() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toString( ));
</script>
</body>
</html>
Why not just use
document.write(str);
I'm trying to understand why you would ever use toString() on a string.
tutorialspoint.com gives this example.
<html>
<head>
<title>JavaScript String toString() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toString( ));
</script>
</body>
</html>
Why not just use
document.write(str);
Share
Improve this question
asked Jun 21, 2016 at 18:01
user1757006user1757006
7753 gold badges13 silver badges25 bronze badges
5
|
4 Answers
Reset to default 8toString()
method doesn't make any practical sense when called on a "pure" sring, like "Apples are round, and Apples are Juicy."
.
It may be useful when you need to get the string representation of some non-string value.
// Example:
var x = new String(1000); // converting number into a String object
console.log(typeof x); // object
console.log(typeof x.toString()); // string
console.log(x.toString()); // "1000"
The String object overrides the toString() method of the Object object; it does not inherit Object.prototype.toString(). For String objects, the toString() method returns a string representation of the object and is the same as the String.prototype.valueOf() method.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toString
string.toString()
is useful if you are not entirely certain wether you might get a Number or a String, and if you definitely need a string to proceed with other calculations, e.g. String functions like .includes
or .split
.
Even if you don't use the toString
function, it is invoked (implicitly) to get the value that is used for the document.write()
function.
There's no difference. I think that they used the toString
function just to emphasize that it exists. Every object in javascript has a toString
function, because it's defined on Object
's prototype, like explained here.
The difference is that the String
type overrides the original toString
function, otherwise the result would be "[object String]
".
toString()
.... Also there is description about the return value Returns a string representing the specified object. . Also I would always prefer MDN documentation – Pranav C Balan Commented Jun 21, 2016 at 18:04str
. Which feels “impure” and practical, and so, very javascripty. – Toph Commented Jan 10, 2018 at 16:41