Question
What are the steps to create a deep copy of an object in JavaScript while ensuring that the original and cloned objects do not share references?
// Example of deep copy using structuredClone
const originalObj = { a: 1, b: { c: 2 } };
const deepCopiedObj = structuredClone(originalObj);
console.log(deepCopiedObj.b === originalObj.b); // false
Answer
Creating a deep copy of an object involves duplicating an object and all its nested properties (if any) so that modifications to the clone do not affect the original object. This technique is important in programming, especially in JavaScript, where reference types can lead to unintended mutations. In this guide, we’ll explore several methods for achieving deep copies in JavaScript, ensuring that the original and the cloned objects do not share references.
// Deep copy using JSON methods
const original = { x: 1, y: { z: 2 } };
const clone = JSON.parse(JSON.stringify(original));
console.log(clone.y === original.y); // false
Causes
- Direct assignment creates a reference, not a copy (e.g., `let clone = obj` does not create a new object).
- Nested objects or arrays can lead to shared references, causing the deep copy to fail.
Solutions
- Use JSON methods: `JSON.parse(JSON.stringify(obj))` (works for JSON-serializable objects).
- Implement a recursive function to copy properties and nested structures.
- Utilize built-in methods like `structuredClone(obj)`, which was introduced in recent JavaScript versions.
Common Mistakes
Mistake: Using shallow copy methods which do not copy nested objects.
Solution: Always use a method that recursively copies all properties.
Mistake: Assuming JSON methods can copy functions or special object types (e.g., Date).
Solution: Use `structuredClone` or a custom deep copy function to handle these types.
Helpers
- deep copy JavaScript
- clone object JavaScript
- JavaScript object deep copy
- copy nested objects JavaScript
- structuredClone JavaScript