Handling Circular References
What you'll learn: How to detect and safely handle circular references when implementing deep clone functions using WeakMap tracking.
When implementing a recursive deep clone, you'll encounter a serious problem: circular references. This happens when an object references itself directly or indirectly through its properties:
const obj = { name: "Alice" };
obj.self = obj; // circular!
Without protection, your recursive clone function would chase this reference forever, causing a stack overflow. The solution is to track objects you've already cloned using a WeakMap.
Why WeakMap?
A WeakMap lets you map original objects to their clones. It's perfect here because:
- Keys are objects (not strings)
- References are weak (won't prevent garbage collection)
- Fast lookup to check "have I cloned this before?"
The Pattern
function deepClone(value, seen = new WeakMap()) {
// Primitives pass through
if (value === null || typeof value !== 'object') {
return value;
}
// Check if we've seen this object before
if (seen.has(value)) {
return seen.get(value); // Return existing clone
}
// Create new clone
const clone = Array.isArray(value) ? [] : {};
// Register BEFORE recursing (crucial!)
seen.set(value, clone);
// Now recurse safely
for (let key in value) {
clone[key] = deepClone(value[key], seen);
}
return clone;
}
// Now safe with circular references
const obj = { name: "Alice" };
obj.self = obj;
const cloned = deepClone(obj);
console.log(cloned.self === cloned); // true (preserved structure)
Notice we register the clone in seen before recursing. This ensures that if we encounter the same object again during recursion, we return the partially-built clone rather than creating a new one.
Key Takeaway: Use a WeakMap to track original-to-clone mappings in deep clone implementations, registering each object before recursing to safely handle circular references and preserve object identity relationships.