Deep Clone with JSON
Serialize to JSON then parse back to create a deep clone of an object. This is the simplest approach but loses functions, Dates, undefined, and circular references.
Serialize to JSON then parse back to create a deep clone of an object. This is the simplest approach but loses functions, Dates, undefined, and circular references.
const original = { user: { name: "Alice", roles: ["admin"] } };
// Deep clone
const clone = JSON.parse(JSON.stringify(original));
clone.user.roles.push("editor");
console.log(original.user.roles); // ["admin"] — untouched
console.log(clone.user.roles); // ["admin", "editor"]
// Modern alternative: structuredClone()
const clone2 = structuredClone(original);
// Handles Date, Map, Set, circular refs — prefer this!
Use structuredClone() for modern deep cloning — it handles Dates, Maps, Sets, and circular references that JSON clone breaks.
More in JavaScript