SyntaxStudy
Sign Up
JavaScript JSON for Deep Cloning
JavaScript Intermediate 4 min read

JSON for Deep Cloning

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.

Example
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!
Pro Tip

Use structuredClone() for modern deep cloning — it handles Dates, Maps, Sets, and circular references that JSON clone breaks.