JavaScript · Senior · Question 74 of 75
What does a toJSON method on an object do?
class Money {
constructor(cents) { this.cents = cents; }
toJSON() { return (this.cents / 100).toFixed(2); }
}
JSON.stringify({ price: new Money(1999) });- ✓Correct answer:
JSON.stringifyuses its return value instead of the object - here{"price":"19.99"} - 2It parses JSON into the class
- 3It is ignored by
JSON.stringify
Explanation
Date uses toJSON to output ISO strings. For parsing back, pass a reviver to JSON.parse - classes aren't restored automatically.