đ„ Meet structuredClone() â JavaScriptâs Built-in Deep Clone Hero
If youâve ever relied on:
const clone = JSON.parse(JSON.stringify(obj));
...to deep copy JavaScript objects, youâve probably hit some major roadblocks. While this trick works for simple data, it falls apart fast when you're dealing with more complex structures.
â Common Issues with JSON.stringify() and JSON.parse()
- Loses types like Date, Map, Set, RegExp, etc.
- Crashes on circular references
- Drops undefined values
- Converts everything into plain objects
đ Enter structuredClone()
structuredClone() is a native browser and Node.js API designed to deeply clone almost anything. No third-party libraries, no hacksâjust modern JavaScript doing what it should.
â It handles:
- Nested objects and arrays
- Date, Map, Set
- ArrayBuffer, TypedArray
- Circular references
- undefined, RegExp, Blob, File, and more
đ Example
const original = {
date: new Date(),
map: new Map([["key", "value"]]),
set: new Set([1, 2]),
circular: null
};
original.circular = original;
const copy = structuredClone(original);
console.log(copy.date instanceof Date); // true
console.log(copy.map instanceof Map); // true
console.log([...copy.map]); // [["key", "value"]]
console.log(copy.set.has(1)); // true
console.log(copy.circular === copy); // true
â ïž What It Doesnât Support
There are still a few things structuredClone() canât handle:
- Functions
- DOM elements
- WeakMap / WeakSet
- Custom class methods
đ§ Browser & Node Support
â
Chrome 98+, Firefox 94+, Safari 15.4+
â
Node.js 17.4.0+ (or earlier with --experimental flag)
â Not supported in older environments
đŻ Final Thoughts
If you need a safe, reliable, and native way to deep copy structured data in JavaScript, structuredClone() is the tool youâve been waiting for.
No more losing special object types. No more circular reference headaches.
đŹ Have you tried structuredClone() yet? Let me know how youâre using it in your projects!
Top comments (0)