In JavaScript, deep copy and shallow copy refer to how objects (or arrays) are duplicated. They determine whether the copied object shares the same references as the original object or creates entirely new ones.
1. Shallow Copy: A shallow copy creates a new object, but copies only the first level of properties. If the properties of the original object are references (like objects or arrays), these references are copied, not the actual values. This means changes to nested objects in the copy will affect the original object.
Shallow Copy In JavaScript |
Difference:
Shallow Copy: Copies only the first level and shares references for nested objects.
Deep Copy: Copies everything, creating independent nested objects.
Ways to Create Shallow Copies
1. Using the spread operator (...):
2. Using Object.assign:
Ways to Create Deep Copies
1.
1. Using JSON methods:
javascript const deepCopy = JSON.parse(JSON.stringify(original));
2. Using structuredClone (modern method):
javascript
const deepCopy = structuredClone(original); // Works for complex
objects
3. Using libraries (e.g., Lodash's _.cloneDeep):
javascript const deepCopy = _.cloneDeep(original);
No comments:
Post a Comment