0 day streak
javascript / intermediate
Snippet

Deep Cloning with structuredClone

The structuredClone() method provides a native way to create deep copies of JavaScript objects. Unlike JSON.parse(JSON.stringify()), it correctly handles nested objects, arrays, and complex types like Date, Map, or Set.

snippet.js
javascript
1
2
3
4
5
const original = { id: 1, meta: { created: new Date() } };
const copy = structuredClone(original);
console.log(copy !== original); // true
console.log(copy.meta.created instanceof Date); // true
nodejs
Breakdown
1
const copy = structuredClone(original);
Creates a complete, independent deep copy of the original object.
2
copy.meta.created instanceof Date
Verifies that the Date object was preserved as a Date type and not converted to a string.