Course contentsShow
← JavaScript
Lesson 695 of 2,72316. Object Methods and PatternsFree lesson

Manual Deep Clone Strategies

Implementing recursive cloning functions and handling circular references in custom solutions.

Manual Deep Clone Strategies

What you'll learn: How to write your own recursive function to deep clone objects and safely handle circular references.

When structuredClone isn't available or doesn't support your data types, you need a custom solution. Manual deep cloning means writing a recursive function that traverses an object's structure, copying each layer.

The Recursive Pattern

The core idea: check each property's type. If it's a primitive, copy directly. If it's an object or array, recursively clone it:

function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj; // primitives and null
  }
  
  if (Array.isArray(obj)) {
    return obj.map(item => deepClone(item));
  }
  
  const cloned = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      cloned[key] = deepClone(obj[key]);
    }
  }
  return cloned;
}

const original = { user: { name: 'Alice', scores: [1, 2, 3] } };
const copy = deepClone(original);
copy.user.name = 'Bob';
console.log(original.user.name); // 'Alice' — truly independent

Handling Circular References

The tricky part: if an object references itself, naive recursion causes infinite loops. Track visited objects with a WeakMap:

function deepCloneWithCircular(obj, map = new WeakMap()) {
  if (obj === null || typeof obj !== 'object') return obj;
  
  if (map.has(obj)) {
    return map.get(obj); // already cloned
  }
  
  const cloned = Array.isArray(obj) ? [] : {};
  map.set(obj, cloned); // register before recursing
  
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      cloned[key] = deepCloneWithCircular(obj[key], map);
    }
  }
  return cloned;
}

const circ = { name: 'self' };
circ.self = circ;
const safe = deepCloneWithCircular(circ); // no infinite loop

Key Takeaway: Manual deep cloning requires recursion to traverse nested structures and a WeakMap to track visited objects, preventing infinite loops from circular references.