javascript / intermediate
Snippet
Deep Cloning with structuredClone
The structuredClone() method creates a deep clone of a given value using the structured clone algorithm. Unlike shallow copies or JSON.parse hacks, it correctly handles nested objects, arrays, and even types like Date or Map.
snippet.js
1
2
3
4
5
const user = { name: 'Alice', meta: { id: 1 } };const deepCopy = structuredClone(user);deepCopy.meta.id = 2;console.log(user.meta.id); // 1console.log(deepCopy.meta.id); // 2
Breakdown
1
const deepCopy = structuredClone(user);
Creates a complete independent copy of the object and all nested properties.
2
deepCopy.meta.id = 2;
Modifying the clone does not affect the original object.
3
console.log(user.meta.id);
The original value remains unchanged at 1.