Recursive Deep Clone Implementation
You'll learn how to build your own custom deep clone function that recursively copies objects, arrays, and nested structures.
Why Build Your Own?
While structuredClone() and JSON.parse(JSON.stringify()) work for many cases, sometimes you need fine-grained control over what gets cloned and how. A custom recursive function lets you handle edge cases, skip certain properties, or add custom logic during the cloning process.
The Core Recursive Pattern
The idea is simple: check the type of each value. If it's a primitive, just return it (primitives are copied by value). If it's an object or array, create a new container and recursively clone each property or element.
function deepClone(value) {
// Primitives and null return as-is
if (value === null || typeof value !== 'object') {
return value;
}
// Handle arrays
if (Array.isArray(value)) {
return value.map(item => deepClone(item));
}
// Handle plain objects
const cloned = {};
for (const key in value) {
if (value.hasOwnProperty(key)) {
cloned[key] = deepClone(value[key]);
}
}
return cloned;
}
const original = { a: 1, b: { c: 2 }, d: [3, { e: 4 }] };
const copy = deepClone(original);
copy.b.c = 99;
console.log(original.b.c); // 2 (unaffected)
How It Works
Think of it like exploring a nested file system: when you hit a folder (object/array), you create a new empty folder and recursively copy everything inside. When you hit a file (primitive), you just copy it directly.
Key Takeaway: A recursive deep clone walks through every level of nested structures, creating new containers and copying values independently, giving you full control over the cloning process.