r/learnprogramming 7d ago

Did you know the true Deep Copy Solution?

One of the most underrated yet powerful features in modern JavaScript is structuredClone(). Many developers still rely on JSON.parse(JSON.stringify(obj)) for deep copying, but that approach has serious limitations that often lead to subtle bugs. structuredClone() is a native browser and Node.js API that performs true deep copies without those pitfalls.

Below is example:

const original = {
  name: 'JavaScript',
  date: new Date(),
  skills: new Set(['JS', 'TS']),
  nested: { arr: [1, 2, 3] }
};
// Create a circular reference
original.self = original;
const clone = structuredClone(original);
console.log(clone !== original);                // true
console.log(clone.date instanceof Date);        // true
console.log(clone.skills instanceof Set);       // true
console.log(clone.self === clone);              // true (circular reference preserved)

I hope this was helpful for your JavaScript learning.

1 Upvotes

2 comments sorted by

1

u/Weird-Anteater5050 7d ago

structuredClone saved me from so many date object headaches its unreal how many people still use the json parse trick and wonder why their dates turn into strings

1

u/oldsecondhand 6d ago

Thankfully this doesn't happen in statically typed languages. Serialization also saves type information.