Deep and Shallow Copy in Javascript
In JavaScript objects and arrays are reference types, means that when we copy them, we might still be referencing the same memory location instead of creating a completely a new object or array. If we don't handle copying correctly, we may accidentally end up modifying the original ones.
Shallow Copy
A shallow copy creates a new object or array, but it only copies the top-level elements. If there are nested objects or arrays, the copy still holds a reference to the original ones.
Example - Object
const obj1 = {
name: "Alice",
address: { city: "New York", zip: "10001" }
};
// Creating a shallow copy using spread operator
const obj2 = { ...obj1 };
obj2.name = "Bob"; // This changes only the copy
obj2.address.city = "Los Angeles"; // This also changes obj1.address.city!
console.log(obj1.name); // "Alice" (Unchanged)
console.log(obj1.address.city); // "Los Angeles" (Changed due to shared reference)
✅ Shallow Copy Methods for Objects
- Spread operator
{ ...obj }
Object.assign({}, obj)
Example - Array
const arr1 = [[1, 2, 3], [4, 5, 6]];
// Creating a shallow copy using spread operator
const arr2 = [...arr1];
arr2[0].push(99); // This modifies arr1 too
console.log(arr1); // [[1, 2, 3, 99], [4, 5, 6]] Original array is changed
console.log(arr2); // [[1, 2, 3, 99], [4, 5, 6]]
✅ Shallow Copy Methods for Arrays
[...arr]
(Spread operator)arr.slice()
arr.concat()
Deep Copy
A deep copu creates a new object or array and recursively copies all nested objects or array. This ensure that the copied object is completely independent of the original one.
Example - Object
const obj1 = {
name: "Alice",
address: { city: "New York", zip: "10001" }
};
// Creating a deep copy using JSON method
const obj2 = JSON.parse(JSON.stringify(obj1));
obj2.address.city = "Los Angeles"; // Only obj2 changes
console.log(obj1.address.city); // "New York" Original remains unchanged
console.log(obj2.address.city); // "Los Angeles"
✅ Deep Copy Methods for Objects
JSON.parse(JSON.stringify(obj))
Works only for simple objects_.cloneDeep(obj)
Lodash, handles complex objects
Example - Array
const arr1 = [[1, 2, 3], [4, 5, 6]];
// Creating a deep copy using JSON method
const arr2 = JSON.parse(JSON.stringify(arr1));
arr2[0].push(99); // ✅ Only arr2 changes
console.log(arr1); // [[1, 2, 3], [4, 5, 6]] Original unchanged
console.log(arr2); // [[1, 2, 3, 99], [4, 5, 6]]
✅ Deep Copy Methods for Array
JSON.parse(JSON.stringify(obj))
Works only for simple objects_.cloneDeep(obj)
Lodash, handles complex objects
Recursive Deep Copy Function for object and array
function deepCopy(value){
if(value === null || typeof value !== 'object'){
return value;
}
// If it'a an array
if(Array.isArray(value)){
return value.map(item=> deepCopy(item)) // Recursively copy each element in array
}
// If it's an object, recursively copy each key-value pair
const clone = {};
for (let key in value) {
if (value.hasOwnProperty(key)) {
clone[key] = deepClone(value[key]);
}
}
return clone;
}