Clean Markup

Native Deep Copying in JavaScript with structuredClone

Native Deep Copying in JavaScript with structuredClone

Deep copying nested data structures in JavaScript has long been fraught with compromises. The ubiquitous JSON.parse(JSON.stringify(object)) trick silently drops undefined, strips custom classes, converts Date objects to strings, and violently crashes on circular references. Third-party helpers like lodash.cloneDeep inflated bundle sizes.

The standardized structuredClone() global function brings native, algorithmic deep copying directly to all modern JavaScript environments.

Example

const original = {
  id: 'order_101',
  timestamp: new Date(),
  tags: new Set(['express', 'fragile']),
  metadata: new Map([['region', 'EU']]),
};

// Circular reference
original.self = original;

const deepCopy = structuredClone(original);
console.log(deepCopy.timestamp instanceof Date); // true
console.log(deepCopy.tags instanceof Set);       // true
console.log(deepCopy.self === deepCopy);         // true

Implementation

// structuredClone transfers transferable objects (like ArrayBuffer) with zero memory copy overhead
const buffer = new ArrayBuffer(1024);
const clonedBuffer = structuredClone(buffer, { transfer: [buffer] });
console.log(buffer.byteLength);       // 0 (transferred)
console.log(clonedBuffer.byteLength); // 1024

Main Point: Replace JSON.parse(JSON.stringify()) with structuredClone() for lossless deep copying of Dates, Sets, Maps, and circular references.

Credits

Photo by Fumikazu Sato on Unsplash

← Home