When working with JavaScript, understanding the difference between shallow copy and deep copy is essential for effective manipulation of objects and arrays. Let’s delve into what these terms mean and how to implement each type of copy in your code.
Shallow Copy
A shallow copy creates a new object or array that holds the same values as the original. However, if the original contains nested objects or arrays, the shallow copy only copies the references to these nested structures, not the structures themselves. This means changes to the nested objects or arrays in the copied structure will also affect the original.
Examples of Shallow Copy Methods:
- Spread Operator ({…})
const original = { a: 1, b: { c: 2 } };
const shallowCopy = { ...original };
Here, shallowCopy is a new object, but shallowCopy.b still references the same object as original.b.
2.Object.assign()
const shallowCopy = Object.assign({}, original);
- Array slice Method
const originalArray = [1, 2, 3];
const shallowCopyArray = originalArray.slice();
Deep Copy
A deep copy creates a new object or array that is a complete, independent clone of the original, including all nested objects and arrays. Changes to the deep copy do not affect the original and vice versa.
Examples of Deep Copy Methods:
- JSON.stringify() and JSON.parse()
const original = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(original));
This method serializes the object to a JSON string and then parses it back to a new object. However, it does not handle functions, undefined, or circular references.
2.Recursive Function
function deepCopy(obj) { if (obj === null || typeof obj !== 'object') return obj; const copy = Array.isArray(obj) ? [] : {}; for (let key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = deepCopy(obj[key]); } } return copy;
}
- StructuredClone() (in modern JavaScript environments)
const deepCopy = structuredClone(original);
When to Use Each
Shallow Copy: Suitable for simple objects or arrays without nested structures. It’s faster and uses less memory. Use it when you need a quick copy where changes to nested objects should reflect in both the original and the copy.
Deep Copy: Necessary for complex objects or arrays with nested structures. It ensures that changes to the copy do not affect the original. Use it when you need completely independent clones.
Understanding these differences helps prevent bugs that arise from unintended shared references and ensures data integrity in your applications