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) });

Explanation

Date uses toJSON to output ISO strings. For parsing back, pass a reviver to JSON.parse - classes aren't restored automatically.

Further reading

Problem with a question

JavaScript · Senior · question 74

Test yourself

Take the JavaScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz