Deep Clone With Structured Clone Algorithm

Deep clone objects using structuredClone with fallback for older runtimes handling cycles and typed arrays.

JavascriptData Integrity

Code

javascriptsnippet
1 line
export function deepClone(obj){if(typeof structuredClone==='function'){try{return structuredClone(obj);}catch{}}return cloneFallback(obj,new WeakMap());}function cloneFallback(obj,seen){if(obj===null||typeof obj!=='object')return obj;if(seen.has(obj))return seen.get(obj);if(Array.isArray(obj)){const arr=[];seen.set(obj,arr);for(const i of obj)arr.push(cloneFallback(i,seen));return arr;}if(Buffer.isBuffer(obj))return Buffer.from(obj);if(obj instanceof Date)return new Date(obj);if(obj instanceof Map){const m=new Map();seen.set(obj,m);for(const[k,v]of obj)m.set(cloneFallback(k,seen),cloneFallback(v,seen));return m;}const clone={};seen.set(obj,clone);for(const[k,v]of Object.entries(obj))clone[k]=cloneFallback(v,seen);return clone;}

What the code does

Count the functions deepClone and cloneFallback as the entire surface area of Deep Clone With Structured Clone Algorithm.

What comes back is a new object, not a reference to anything passed in.

What to watch for

  • The guard obj===null||typeof obj!=='object' short-circuits the flow with an early return when its condition holds.

Using it in your own code

Entry signature: export function deepClone(obj)

deepClone is what another module would consume; nothing else here is load-bearing for callers.

Interactive Tools for This Topic

FAQ

Does `deepClone` modify its input?
It does not. Inputs are only read; the return value is freshly built.
Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `deepClone`, `cloneFallback` at load time.