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
Top comments (1)
Thanks! Your post is like timely Providence. Im relatively new to Javascript and just today I was writing a new constructor for an object that uses a 3 dimensional array in which some elements are complex objects. In testing it I found some "undefined"s. I was going at it like it was an issue with my this.s and arrow functions inside a constructor or a scope issue. It took me about 30 years to learn that instead of chugging caffiene and taking 2.2 minute naps between google, StackOverflow, rewriting blocks and kludging, sometimes its best to just walk away for a while. Especially when the woman is huffing and looking at me sideways. I did so. Yours is the first post I looked at here this morning and viola! I "clone" a complex array of live data into the object with assign and it wasnt creating the data with the structure. The code is deep and not as
elegant as I'd like. Its the thing that, when I look at it in 10 years will think "WTF was I trying to do here"? While I didnt use any of the methods you described, and just changed the way I got the data but I saved your post and added the code into my little code search app for future reference.
Ive been a programmer since 1976 but never had a need or the inclination to learn Javascript. It was a data delivery boy for HTML back in the mid 90s. I re-looked at it last Christmas and was amazed at how powerful and (mostly) intuitive it is. But Ive got a long way to go. Your post flipped the light on in my head and really helped me,.so thank you very much.