javascript / intermediate
Snippet
Safe Deep Cloning with structuredClone
Unlike the JSON.parse(JSON.stringify()) hack, structuredClone creates a true deep copy that handles circular references and complex types like Date, Map, and Set.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
const original = {user: 'Markus',roles: new Set(['admin', 'editor']),metadata: { created: new Date() }};const copy = structuredClone(original);copy.roles.add('guest');console.log(original.roles.has('guest')); // falseconsole.log(copy.metadata.created instanceof Date); // true
nodejs
Breakdown
1
structuredClone(original)
Performs a native deep clone of the entire object graph.
2
copy.roles.add('guest')
Modifying the copy does not affect the original Set.