JS Built-ins
← Date113 / 120
DatetoJSONbeginner

toJSON() β€” returns a string

πŸ“– Usage Example
const d = new Date('2024-01-15T00:00:00.000Z')
d.toJSON()  // β†’ '2024-01-15T00:00:00.000Z'
JSON.stringify({ date: d })  // uses toJSON()

Use toJSON() to get the ISO 8601 UTC string representation of a Date; it is called automatically by JSON.stringify.

Date.prototype.toJSON()

toJSON() always returns a string.

Challenge: Verify that typeof new Date(0).toJSON() returns 'string'.

πŸ’‘ Hints (1)
  • β€’ toJSON() returns a string primitive β€” the same ISO format used for JSON serialisation