DEV Community

loading...

Discussion on: JavaScript Quiz Part 2

Collapse
loilo profile image
Florian Reuschel

Interesting fact for completeness: The JSON counterpart of toString() is toJSON(). If an object has a toJSON() method, it will be evaluated and its result will be stringified instead:

pony.toJSON = function () {
  return this.name
}

JSON.stringify(pony) === '"Twighlight Sparkle"'
Collapse
avalander profile image
Avalander

Nice! I wasn't aware of that!

Then we could potentially override that method to get [object Object] when converting it to JSON.

pony.toJSON = function () {
    return this.toString()
}

JSON.stringify(pony) // '[object Object]'
Thread Thread
loilo profile image
Florian Reuschel

That sounds... useful? 🙈
But yeah, it's a feature that I as well only discovered after many years of JS experience and since have never used in production. It's pretty cool though.

Thread Thread
loilo profile image
Florian Reuschel

Oh, and also the result would in fact be "[object Object]". The quotes are part of the serialized result (since it needs to be valid JSON).

Thread Thread
avalander profile image
Avalander

That sounds... useful? 🙈

I mean, the specification is that the object gets converted to a string. About the actual content of the string, the OP said nothing 😝