Everything that’s an Object is going to either inherit Object.prototype.toString() (mdn) or provide its own implementation.
A String is an Object, so it’s going to have a toString() method. It doesn’t inherit Object’s implementation, but provides one that’s sort of a no-op / identity function but not quite.
So, the thing is that when you say const someString = "test string", you’re not actually creating a new String object instance and assigning it to someString, you’re creating a string (lowercase s!) primitive and assigning it to someString:
Compare this with creating a newString("bla"):
In Javascript, primitives don’t actually have any properties or methods, so when you call someString.toString() (or call any other method or access any property on someString), what happens is that someString is coerced into a String instance, and then toString() is called on that. Essentially it’s like going new String(someString).toString().
Now, what String.prototype.toString() (mdn) does is it returns the underlying string primitive and not the String instance itself.
Why? Fuckin beats me, I honestly can’t remember what the point of this is because I haven’t been elbow-deep in Javascript in years, but regardless this is the logic behind String’s toString().
Everything that’s an
Object
is going to either inheritObject.prototype.toString()
(mdn) or provide its own implementation.A
String
is anObject
, so it’s going to have atoString()
method. It doesn’t inheritObject
’s implementation, but provides one that’s sort of a no-op / identity function but not quite.So, the thing is that when you say
const someString = "test string"
, you’re not actually creating a newString
object instance and assigning it tosomeString
, you’re creating astring
(lowercases
!) primitive and assigning it tosomeString
:Compare this with creating a
new String("bla")
:In Javascript, primitives don’t actually have any properties or methods, so when you call
someString.toString()
(or call any other method or access any property onsomeString
), what happens is thatsomeString
is coerced into aString
instance, and thentoString()
is called on that. Essentially it’s like goingnew String(someString).toString()
.Now, what
String.prototype.toString()
(mdn) does is it returns the underlyingstring
primitive and not theString
instance itself.Why? Fuckin beats me, I honestly can’t remember what the point of this is because I haven’t been elbow-deep in Javascript in years, but regardless this is the logic behind
String
’stoString()
.