Almost every JavaScript developer uses JSON.stringify(data) and JSON.parse(str). However, few realize that both methods accept a powerful second argument: the Replacer and the Reviver. These transform functions enable masking sensitive fields, formatting custom types, and restoring Date and Map instances during serialization.
The syntax for JSON.stringify:
The replacer function is called for every key-value pair. Returning undefined omits the property from the output:
Passing an array of property names acts as an exact whitelist:
By default, JSON.parse() converts ISO date strings into plain strings. A Reviver function inspects each key-value pair and transforms it back into a native JavaScript object:
By default, attempting to serialize a BigInt throws TypeError: Do not know how to serialize a BigInt. A replacer handles this cleanly:
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| GraphQL Queries, Mutations & Subscriptions | Circular Reference Handling & Custom Serialization |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.