javascript / intermediate
Snippet
Deep Cloning Objects with structuredClone
The structuredClone global function creates a deep copy of a value, handling circular references and built-in objects like Date, Set, and Map correctly, unlike JSON.parse(JSON.stringify()).
snippet.js
1
2
3
4
5
6
7
8
9
10
const original = {id: 1,metadata: { created: new Date() },tags: new Set(['js', 'next'])};const copy = structuredClone(original);copy.metadata.created.setFullYear(2025);console.log(original.metadata.created.getFullYear()); // 2026
nextjs
Breakdown
1
const copy = structuredClone(original)
Creates a true deep copy where nested objects are also cloned.
2
tags: new Set(['js', 'next'])
Complex types like Set are properly preserved during the cloning process.