Question 18

Question

How would you implement a custom deepCopy() method?

Answer

Using JSON.parse(JSON.stringify()) is a common technique for creating deep copies of objects in JavaScript. Here's a breakdown of how to implement it:

function deepCopy(obj) {
  return JSON.parse(JSON.stringify(obj));
}

Explanation:

  1. JSON.stringify(obj): This method takes your object (obj) and converts it into a JSON string representation. This process essentially flattens nested objects into key-value pairs within the string.

  2. JSON.parse(...): This method then takes the JSON string and parses it back into a JavaScript object. Because of how JSON.stringify handles objects, this creates a completely new copy with its own references. Changes made to the copied object won't affect the original.

Example:

const originalObject = {
  name: "Alice",
  age: 30,
  address: {
    street: "123 Main St",
    city: "Anytown"
  }
};

const copiedObject = deepCopy(originalObject);

copiedObject.name = "Bob"; // Change the name in the copy
console.log(originalObject); // Still outputs: { name: "Alice", age: 30, ... }

Important Notes:

  • Circular References: JSON.stringify() and JSON.parse() will handle simple circular references (objects referencing each other). However, for complex nested cycles, you might need a more robust solution.

  • Non-Serializables: Be mindful that not all data types are serializable by JSON. For example, functions, custom objects with non-serializable properties, or large binary data might cause issues.

Last updated