JavaScript · Senior · Question 22 of 75
How do you serialize an object with circular references to JSON?
- ✓Correct answer: Via a
replacerinJSON.stringify, tracking visited objects in aWeakSet - 2Plain
JSON.stringifyhandles it: it replaces cycles withnull - 3Such an object can't be serialized in any way
Explanation
JSON.stringify throws TypeError: Converting circular structure to JSON. In a replacer you can skip already-seen objects or replace them with a marker reference (as libraries like flatted do). For copying within JS, structuredClone works - it supports cycles.