String.prototype.toString() | JS to string
TheString[1]objectoverridesthetoStringmethodofObject[2];itdoesnotinheritObject.prototype.toString()[3].ForStringvalues,thetoStringmethodreturnsthestringitself(ifitsaprimitive)orthestringthattheStringobjectwraps.IthastheexactsameimplementationasString.prototype.valueOf()[4].ThetoString()methodrequiresitsthisvaluetobeaStringprimitiveorwrapperobject.ItthrowsaTypeError[5]forotherthisvalueswithoutattemptingtocoercethemtostringvalues.BecauseStringdoesnthavea[@@toPrimitive]()[6]method,JavaScriptcal...
The String[1] object overrides the toString method of Object[2]; it does not inherit Object.prototype.toString()[3]. For String values, the toString method returns the string itself (if its a primitive) or the string that the String object wraps. It has the exact same implementation as String.prototype.valueOf()[4].
The toString() method requires its this value to be a String primitive or wrapper object. It throws a TypeError[5] for other this values without attempting to coerce them to string values.
Because String doesnt have a [@@toPrimitive]()[6] method, JavaScript calls the toString() method automatically when a String object is used in a context expecting a string, such as in a template literal[7]. However, String primitive values do not consult the toString() method to be coerced to strings[8] — since they are already strings, no conversion is performed.
String.prototype.toString = () => "Overridden"; console.log(`${"foo"}`); console.log(`${new Str...