String.prototype.toString()
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
ThetoString()
method ofString
values returns this string value.
Try it
const stringObj = new String("foo");console.log(stringObj);// Expected output: String { "foo" }console.log(stringObj.toString());// Expected output: "foo"
Syntax
toString()
Parameters
None.
Return value
A string representing the specified string value.
Description
TheString
object overrides thetoString
method ofObject
; it does not inheritObject.prototype.toString()
. ForString
values, thetoString
method returns the string itself (if it's a primitive) or the string that theString
object wraps. It has the exact same implementation asString.prototype.valueOf()
.
ThetoString()
method requires itsthis
value to be aString
primitive or wrapper object. It throws aTypeError
for otherthis
values without attempting to coerce them to string values.
BecauseString
doesn't have a[Symbol.toPrimitive]()
method, JavaScript calls thetoString()
method automatically when aString
object is used in a context expecting a string, such as in atemplate literal. However, Stringprimitive values do not consult thetoString()
method to becoerced to strings — since they are already strings, no conversion is performed.
String.prototype.toString = () => "Overridden";console.log(`${"foo"}`); // "foo"console.log(`${new String("foo")}`); // "Overridden"
Examples
Using toString()
The following example displays the string value of aString
object:
const x = new String("Hello world");console.log(x.toString()); // "Hello world"
Specifications
Specification |
---|
ECMAScript® 2026 Language Specification # sec-string.prototype.tostring |