r/learnjavascript • u/ModeCommercial5464 • 8h 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.