Cloning an object means creating a copy of the object. There are two types:
1️⃣ Shallow Copy
- Copies only the first level of the object.
- Nested objects or arrays are shared between original and copy.
- Changes in nested objects affect both.
Example of Shallow Copy:
const original = { name: "Alice", address: { city: "Paris" } };
const shallowCopy = { ...original };
shallowCopy.address.city = "London";
console.log(original.address.city); // London → changed!
2️⃣ Deep Copy
- Copies all levels of the object.
- Nested objects are completely independent.
- Changes in the copy do not affect the original.
Deep Clone Function (Recursive)
function deepClone(obj) {
if (obj === null || typeof obj !== "object") {
return obj; // return primitive values as is
}
if (Array.isArray(obj)) {
return obj.map(item => deepClone(item)); // clone each array element
}
const clonedObj = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
clonedObj[key] = deepClone(obj[key]); // recursive clone
}
}
return clonedObj;
}
// Example
const original = {
name: "Alice",
address: { city: "Paris", zip: 75000 },
hobbies: ["reading", "traveling"]
};
const cloned = deepClone(original);
cloned.address.city = "London";
cloned.hobbies.push("coding");
console.log(original.address.city); // Paris
console.log(original.hobbies); // ["reading", "traveling"]
⚖️ Key Differences Table
| Feature | Shallow Copy | Deep Copy |
|---|---|---|
| Levels Copied | Only first level | All nested levels |
| Nested Objects | Shared | Independent |
| Example Methods | { ...obj }, Object.assign() |
Custom recursive function, structuredClone() in modern JS |
✅ In Short:
- Shallow copy → quick, but nested objects are linked.
- Deep copy → full independent clone, safe for complex objects.
Note: Modern JS also has
structuredClone(obj)which performs deep cloning.