javascript / intermediate
Snippet
Deep Cloning with structuredClone()
The structuredClone() method creates a deep copy of a value, handling complex objects like Dates, Sets, and nested structures without the limitations of JSON.stringify.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
const userProfile = {name: 'Alice',settings: { theme: 'dark' },joined: new Date(),references: new Set([1, 2, 3])};const deepCopy = structuredClone(userProfile);deepCopy.settings.theme = 'light';console.log(userProfile.settings.theme); // 'dark' (original is unchanged)console.log(deepCopy.joined instanceof Date); // true
Breakdown
1
const deepCopy = structuredClone(userProfile);
Creates a completely independent copy of the object and all its nested properties.
2
deepCopy.joined instanceof Date
Confirms that structuredClone preserves built-in object types correctly.