JavaScript Snippet

Deep Clone with structuredClone

Difficulty: Medium

Deep cloning is no longer a `JSON.parse(JSON.stringify(x))` hack. Modern runtimes ship `structuredClone`, which handles cycles, Maps, Sets, typed arrays, and Date out of the box. This snippet shows the canonical built-in usage, the JSON fallback for legacy code paths and its real limits, and a hand-rolled recursive clone for when you need to skip specific keys or types. Pick the right tool and stop carrying lodash for one helper.

Code Snippets
/

Deep Clone with structuredClone

Deep Clone with structuredClone

Deep cloning is no longer a `JSON.parse(JSON.stringify(x))` hack. Modern runtimes ship `structuredClone`, which handles cycles, Maps, Sets, typed arrays, and Date out of the box. This snippet shows the canonical built-in usage, the JSON fallback for legacy code paths and its real limits, and a hand-rolled recursive clone for when you need to skip specific keys or types. Pick the right tool and stop carrying lodash for one helper.

JavaScript
Medium
3 snippets
utility
code-template
immutability

325 views

6

structuredClone ships in Node 17+ and every evergreen browser. Unlike a JSON round-trip, it preserves Date, RegExp, Map, Set, ArrayBuffer, typed arrays, and even circular references via the HTML structured-clone algorithm. The clone is fully detached, so mutating the copy never leaks back into the source. The only common types it cannot copy are functions, DOM nodes, and class instances with non-cloneable internal slots (it throws DataCloneError for those). Use this version by default for plain data.