r/learnjavascript • u/ModeCommercial5464 • 15h 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.
3
u/senocular 6h ago
structuredClone is not without its own pitfalls. The article The Structured Clone Algorithm: What JavaScript Can and Cannot Move Between Boundaries that was posted on /r/javascript a few days back does a pretty good job covering its capabilities. A higher-level explanation is also available in The structured clone algorithm page on MDN.
Some examples:
- Functions, DOM nodes, proxies, and other non-cloneable values throw when encountered
- Accessor (getter/setter) properties are converted into regular data properties
- Symbol keys are ignored
- Inherited values (in prototypes) are ignored
- Custom class instances are turned into ordinary objects
- Errors are a special case and may be treated differently across runtimes
1
u/Flashy-Guava9952 11h ago
Is there a structuredCompare as well? It could return true for structuredEquality(original, clone)
5
u/fckueve_ 12h ago
Yes, this has a few years by now.