When working with objects and arrays in JavaScript, it's crucial to understand the difference between shallow copy and deep copy. These methods are used to duplicate objects, but they handle nested structures differently, which can lead to unexpected behavior if not properly understood.
A shallow copy creates a new object or array, but it does not recursively copy nested objects or arrays. Instead, it copies the reference to the nested objects or arrays. This means that changes made to the nested objects in the shallow copy will also affect the original object.
// Original object
const original = {
name: 'John',
address: {
city: 'New York',
country: 'USA'
}
};
// Shallow copy using Object.assign
const shallowCopy = Object.assign({}, original);
// Modify the shallow copy
shallowCopy.name = 'Doe';
shallowCopy.address.city = 'Los Angeles';
// Outputs
console.log(original.name); // 'John' (unchanged)
console.log(original.address.city); // 'Los Angeles' (changed)
// Original array
const originalArray = [1, 2, { a: 3 }];
// Shallow copy using spread operator
const shallowCopyArray = [...originalArray];
// Modify the shallow copy
shallowCopyArray[0] = 9;
shallowCopyArray[2].a = 5;
// Outputs
console.log(originalArray[0]); // 1 (unchanged)
console.log(originalArray[2].a); // 5 (changed)
A deep copy creates a new object or array and recursively copies all nested objects and arrays. This ensures that the copy is completely independent of the original, and changes to the copy do not affect the original object.
// Original object
const original = {
name: 'John',
address: {
city: 'New York',
country: 'USA'
}
};
// Deep copy using JSON methods
const deepCopy = JSON.parse(JSON.stringify(original));
// Modify the deep copy
deepCopy.name = 'Doe';
deepCopy.address.city = 'Los Angeles';
// Outputs
console.log(original.name); // 'John' (unchanged)
console.log(original.address.city); // 'New York' (unchanged)
// Original array
const originalArray = [1, 2, { a: 3 }];
// Deep copy using JSON methods
const deepCopyArray = JSON.parse(JSON.stringify(originalArray));
// Modify the deep copy
deepCopyArray[0] = 9;
deepCopyArray[2].a = 5;
// Outputs
console.log(originalArray[0]); // 1 (unchanged)
console.log(originalArray[2].a); // 3 (unchanged)
Understanding when to use shallow copy versus deep copy is key to effectively managing JavaScript objects and arrays:
While the JSON methods are commonly used, there are other ways to perform a deep copy in JavaScript:
_.cloneDeep
: A utility library that provides a robust deep copy method.Choosing between shallow copy and deep copy depends on your specific use case. For most simple applications, a shallow copy may suffice. However, if you're dealing with complex data structures or need to ensure that your copied objects are fully independent, a deep copy is the way to go.
Published By: Krishanu Jadiya
Updated at: 2024-08-15 01:24:19