Create deep copies of objects and arrays using the native structuredClone() method.

Explanation

  • structuredClone(value): Creates a deep clone of the given value using the structured clone algorithm.
  • Handles complex data types like Date, RegExp, Map, Set, and nested objects.
  • More reliable than JSON.parse(JSON.stringify()) as it preserves data types and handles circular references.
  • Throws an error for non-cloneable values like functions.

Usage

To create deep copies of complex data structures:

const original = {
  name: 'John',
  date: new Date('2024-01-01'),
  hobbies: ['reading', 'coding'],
  settings: {
    theme: 'dark',
    notifications: true
  }
};

// Deep clone using structuredClone
const cloned = structuredClone(original);

// Modify the clone
cloned.name = 'Jane';
cloned.hobbies.push('gaming');
cloned.settings.theme = 'light';

console.log(original.name); // 'John' (unchanged)
console.log(cloned.name); // 'Jane'
console.log(original.date instanceof Date); // true (preserved type)