Deep Copy vs Shallow Copy in JavaScript: Understanding the Difference
Harshit Pandey
React Native | JavaScript | Typescript | Android | IOS | DSA | Node JS
In JavaScript, copying objects and arrays is a common task. However, understanding the difference between shallow copy and deep copy is crucial to avoid unintended side effects in your code
What is a Shallow Copy?
A shallow copy creates a new object or array with the same references as the original. This means that if the original object contains nested objects or arrays, the reference is copied, not the actual values. Any modifications made to the nested objects will reflect in both copies.
const original = {
name: "Harshit",
details: {
age: 25,
city: "Lucknow"
}
};
const shallowCopy = { ...original };
shallowCopy.details.city = "Delhi";
console.log(original.details.city); // Output: "Delhi"
console.log(shallowCopy.details.city); // Output: "Delhi
Other Methods to Create Shallow Copy:
What is a Deep Copy?
A deep copy means that all objects and nested objects are fully cloned, rather than just copying references. Changes in the new object do not affect the
const original = {
name: "Harshit",
details: {
age: 25,
city: "Lucknow"
}
};
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.details.city = "Delhi";
console.log(original.details.city); // Output: "Lucknow"
console.log(deepCopy.details.city); // Output: "Delhi"
领英推荐
Drawbacks of JSON.parse(JSON.stringify()):
How to Properly Create a Deep Copy?
If you need a deep copy that handles complex data types like functions and Date objects, use libraries or recursion.
Method 1: Using Lodash cloneDeep
Lodash provides an efficient deep copy function.
const _ = require('lodash');
const deepCopy = _.cloneDeep(original);
deepCopy.details.city = "Delhi";
console.log(original.details.city); // Output: "Lucknow"
console.log(deepCopy.details.city); // Output: "Delhi"
Method 2: Using a Recursive Function
If you want a custom deep copy function, you can use recursion.
function deepClone(obj) {
if (obj === null || typeof obj !== "object") {
return obj;
}
let copy = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = deepClone(obj[key]);
}
}
return copy;
}
const deepCopy = deepClone(original);
deepCopy.details.city = "Delhi";
console.log(original.details.city); // Output: "Lucknow"
console.log(deepCopy.details.city); // Output: "Delhi"