Custom Deep Copy Function in JavaScript
When working with JavaScript, sooner or later you’ll get into a common problem: copying objects. At first, calling Object.assign() or spreading with { ...obj } may feel like the solution. But those only make shallow copies — and if your object has nested arrays or objects inside, you may get some unpleasant surprises.
Let’s walk through why that happens and try to write a proper custom deep copy function.
The Problem with Shallow Copies
Lets have this simple example:
const user = {
name: “Test User Name”,
hobbies: [“h1”, “h2”],
};
const userCopy = { …user };
userCopy.hobbies.push(“h3”);
console.log(user.hobbies); // -> [“h1”, “h2”, “h3”]
Even though we spread into a new object, the hobbies array is still a shared reference. That’s because the spread operator only copies the reference of nested objects/arrays, not their values.
So if we want a true independent copy, we need a deep copy.
JSON Parse
const deepCopy = JSON.parse(JSON.stringify(obj));
This works surprisingly well for plain data. But it falls apart with things like Date, Map, Set, undefined, functions, or circular references.
Building a Custom Deep Copy Function
We need to handle a few cases carefully:
- Primitive types → (string, number, boolean, null, undefined) → copy as-is.
- Arrays → create a new array and recursively copy each element.
- Objects → create a new object and recursively copy each key.
- Special objects (
Date,RegExp,Map,Set) → handle separately. - Circular references → Avoid infinite loops by tracking references.
Lets code:
Get Sambit Dash’s stories in your inbox
Join Medium for free to get updates from this writer.
function deepCopy(value, trackerMap = new WeakMap()) {
// Handle null or primitive values
if (value === null || typeof value !== “object”) {
return value;
}
// If we’ve this object already (circular ref), return stored copy — we are using trackerMap as weak map to store the reference
if (trackerMap.has(value)) {
return trackerMap.get(value);
}
// Handle Date
if (value instanceof Date) {
return new Date(value);
}
// Handle RegExp
if (value instanceof RegExp) {
return new RegExp(value);
}
// Handle Array
if (Array.isArray(value)) {
const arrCopy = [];
trackerMap.set(value, arrCopy);
value.forEach((item, i) => {
arrCopy[i] = deepCopy(item, trackerMap);
});
return arrCopy;
}
// Handle Map
if (value instanceof Map) {
const mapCopy = new Map();
trackerMap.set(value, mapCopy);
value.forEach((val, key) => {
mapCopy.set(key, deepCopy(val, trackerMap));
});
return mapCopy;
}
// Handle Set
if (value instanceof Set) {
const setCopy = new Set();
trackerMap.set(value, setCopy);
value.forEach((val) => {
setCopy.add(deepCopy(val, trackerMap));
});
return setCopy;
}
// Handle plain objects
const objCopy = {};
trackerMap.set(value, objCopy);
Object.keys(value).forEach((key) => {
objCopy[key] = deepCopy(value[key], trackerMap);
});
return objCopy;
}
Testing the solution with example
Let’s test our solution:
const originalObject = {
name: “Test Name”,
birthdate: new Date(),
favorites: {
colors: [“c1”, “c2”],
},
};
const clonedObject = deepCopy(originalObject);
// Change clone object
clonedObject.favorites.colors.push(“c3”);
// Original stays intact
console.log(originalObject.favorites.colors); // [“c1”, “c2”]
console.log(originalObject.favorites.colors); // [“c1”, “c2”, “c3”]
Wrapping Up
While libraries like Lodash give you _.cloneDeep(), sometimes it’s a good learning to implement on your own. Writing this function from scratch helps you understand how references work in JavaScript, and gives you full control over what gets copied and how.
If you’re working with complex data structures, this custom deep copy function will work always.






