← Back to libraryQuestion 163 of 468
🧩JavaScript CodingIntermediate

Deep Clone an Object

📌 Definition:

Produce a fully independent copy of a nested object so mutating the copy never affects the original.

📖 Detailed Explanation:

Spread and Object.assign are shallow. Use the built-in structuredClone() for a true deep copy. JSON.parse(JSON.stringify()) also deep-copies but drops functions/undefined and mangles Dates; a manual recursive clone handles custom cases.

💻 Solutions:
// Modern built-in (best default):
const clone = structuredClone(obj);

// Manual recursive clone:
function deepClone(value) {
  if (value === null || typeof value !== 'object') return value;
  if (Array.isArray(value)) return value.map(deepClone);
  return Object.fromEntries(
    Object.entries(value).map(([k, v]) => [k, deepClone(v)])
  );
}
🔑 Key Points:
  • structuredClone() is the modern deep-copy built-in
  • Spread/Object.assign are SHALLOW (nested refs shared)
  • JSON round-trip loses functions/undefined, breaks Dates
  • Manual clone needed for class instances / special types
🌍 Real-World Example:

Deep cloning isolates a base test fixture so each test can mutate its own copy without polluting shared state across the suite.

🎯 Scenario-Based Interview Question:

A team deep-clones config with JSON.parse(JSON.stringify(config)) and their Date field becomes a string, breaking comparisons. Why?