To master JavaScript, it is important to understand the difference between deep copying and shallow copying. With the help of both of these, we can work with complex data structures.
In this article, we will teach you what the difference is between deep copy and shallow copy in JavaScript. The purpose of both is the same, but it is necessary to decide which one to use when.
Let us understand the difference between deep copy and shallow copy with a code example.
Table of contents
- What is deep copy?
- What is shallow copy?
- What is the difference between deep copy and shallow copy?
- When should I use a deep copy?
- When should I use a Shallow copy?
- Which is the best for copying object properties: deep copy or shallow copy?
1. What is deep copy?
A deep copy in JavaScript involves creating a completely independent duplicate of an object or array, including all nested objects or arrays within it. This ensures that changes made to the copied object do not affect the original object.
You can create your own deep copy by using these three popular methods.
- Using JSON methods:
- Using libraries like Lodash:
- Using a custom recursive function:
2. What is shallow copy?
A shallow copy in JavaScript involves creating a duplicate of an object or array, but only at the top level. Nested objects or arrays within the copied object still retain references to the original nested objects or arrays. This means that changes made to the nested objects or arrays in the copied object will directly affect the original object.
You can create a shallow copy by using these two popular methods.
- Spread Operator:
- Object.assign():
3. What is the difference between deep copy and shallow copy?
Understanding the difference between shallow and deep copy in JavaScript is important, particularly when you are handling intricate data structures. To improve comprehension, let's see what is the difference between shallow and deep copy.
This is only two points, but it explains the difference between deep and shallow copy very clearly.
- Deep copy ensures that the original object's properties or their nested object property remain the same, even if changes are made to the original object's properties or their nested object properties.
- A shallow copy ensures that the original object's properties remain the same. But the main important thing is when you change the property of a nested object in the copied object has an immediate effect on the corresponding property in the original object's nested structure.
Deep Copy:
- Creating a complete duplicate of an object or array, including all its nested objects or arrays.
- Any changes made to the copy or its nested objects won't affect the original.
- Ensures that modifications to the copy won't mess with the original object's data.
Example for your better understanding
// Original object
const originalObject = {
A: 1,
B: 2,
nestedObject: {
C: 3,
D: 4
}
};
// Deep copy using JSON.parse(JSON.stringify())
const deepCopyObject = JSON.parse(JSON.stringify(originalObject));
// Modifying the A property of the deepCopyObject
deepCopyObject.A = 5;
// Modifying the C property of the nested object within deepCopyObject
deepCopyObject.nestedObject.C = 5;
// Outputting both the original and deep copied objects
console.log("Original Object:", originalObject);
console.log("Deep Copied Object:", deepCopyObject);
// Original Object: { A: '1', B: 2, nestedObject: { C: '3, D: '4' } }
// Deep Copied Object: { A: '5', B: 2, nestedObject: { theme: '5, language: '4' } }
In the above example when we modify the A property with deepCopyObject (deepCopyObject.A = 5;), it only affects the "A" property in the copied object not in the original object. In the original object, A property value is the same (originalObject.A = 1;).
Similarly, when we modify the "C" property of the nested object with deepCopyObject (deepCopyObject.nestedObject.C = 5;), it only affects the C property within the copied nested object not in the original object. In the nested object of the original object C property value is the same (originalObject.nestedObject.C = 3;).
But in the shallow copy something is different let's see how shallow copy is different than deep copy.
Shallow Copy:
With the shallow copy, we are creating a copy of an object or array at the top level only, without impacting the original object. The nested objects or arrays within the copied object still point to the original nested objects or arrays. But if you are doing any modifications to the nested objects or arrays in the copied object it will directly impact the original object.
So when we use deep copy instead of shallow copy, the original nested object maintains the same property value, only the copied object will change.
In other words, when you change something inside a nested part (like an object or array) of the original object, the same change will happen to the original object itself if you are using a shallow copy. This is the main difference between deep copy and shallow copy.
Example for your better understanding
// Original object with nested structure
const originalObject = {
A: 1,
B: 2,
nestedObject: {
C: 3,
D: 4
}
};
// Shallow copy using spread oparetore
const shallowCopyObject = { ...originalObject };
// Modifying the A property of the shallowCopyObject
shallowCopyObject.A = 5
// Modifying the C property of the nested object within shallowCopyObject
shallowCopyObject.nestedObject.C = 5;
// Output both the original and shallow copied objects
console.log(originalObject);
console.log(shallowCopyObject);
// { A: '1', B: 2, nestedObject: { C: '5, D: '4' } }
// { A: '5', B: 2, nestedObject: { theme: '5, language: '4' } }
In the given example, when we change the "A" property value with the shallowCopyObject (shallowCopyObject.A = 5;), it only affects the A property value in the copied object. The A property in the original object remains the same.
But the main point here is that when we change the value of the C property in the nested object with the shallowCopyObject (shallowCopyObject.nestedObject.C = 5;), it directly affects the C property value in the nested object of the original object.
4. When to use deep copy?
Deep copying is really important when you're dealing with complicated data structures or objects that have lots of layers inside. It makes sure that any changes you make to a copy of the object won't mess with the original. We can use Deep copy whenever we need to handle different states, adjust data, or pass it between different parts of our app.
5. When to use shallow copy?
Shallow copy is typically used when you want to duplicate an object or array, but only at the top level (non-nested object). It's useful when you need a quick and lightweight way to clone an object without deeply copying its nested properties or arrays.
6. Which is the best for copying object properties deep copy or shallow copy?
The specific requirements of your application will determine whether deep copy or shallow copy is best. But I will give you some approach so you can take action.
- When you need an independent copy of an object or array that includes all nested properties or arrays, deep copy is the best option.
- On the other hand, if you only require a duplicate of an object or array's top-level structure and not its nested properties, a shallow copy is better.
Both have their own benefits, so you can decide which one to use according to your project.
Conclusion
The deep copy method creates an independent duplicate of an object or array, preserving all nested properties. Ideal for scenarios where maintaining data integrity is paramount. The Shallow copy replicates only the top-level structure(non-nested structure), maintaining references to nested properties. Suitable when you need a basic copy without delving into nested structures.
Hope you've grasped the concept of deep copy VS shallow copy. If you found this article helpful, kindly forward this post to your developer friends so they can benefit from it as well. If you have questions then drop them in the question given below, and you will get response as soon as possible.