Deep copy and Shallow copy

Hi Team,

Can anyone explain the difference between deep copy and shallow copy in Javascript with some examples ?

Thank you @A100D-JS

But these files gives more methods over the same topic.

Deep copy V/s Shallow copy example methods

This video is the explanation of the code in github you’ve just sent me earlier :

I’ve never heard about shallow or deep copying in javascript but the concept is similar to what this video is taking about and it’s more up to date i think.
So, take a look at this and let me know if that was useful :

@A100D-JS I already had a look on both and the first one was clear. Thank you

Then…, why did you ask the question in the first place if you already know what the concept is all about ? :thinking:
I don’t get it :confused:

1 Like

After responding you, I had a look into the internet. and I expected any lecture from Mosh regarding the topic, anyway Thank you

Shallow Copy: Does not copy the content of object_1 to object_2, it just makes object_2 to point to the content of object_1. Any changes made by any of the two objects will affect both because they are pointing to a single memory address.

Deep Copy: Copies the content of object_1 to object_2. Means object_2 has been allocated to another memory location with the same content as object_1, and both are independent of changes.

1 Like

Perfect @MQasim :grinning:

If you use the assignment operator (=) on an Object or Array then it will be copied by reference.

If you use the spread operator (…) or Object.assign() this will create a shallow copy.

A shallow copy refers to the fact that only one level is copied, and that will work fine for an array or object containing only primitive values.

For objects and arrays containing other objects or arrays, copying these objects requires a deep copy. Otherwise, changes made to the nested references will change the data nested in the original object or array.

There is a really good article about this by Dr. Derek Austin here

Deep copy is a value copy, Shallow copy is an address copy. The mess will be happened when cloning an object(Json). Because the objects usually designed to be nested, we can only copy one level using the speaded operator.

The meaning of knowing this, I think, you will know how to fix the bug when code crashed. And it will be often asked in interviews, like design a code to deep copy an object by you own.

But in real life, I never code myself to deep-copy an object. I use lodash, hahaha :laughing:

1 Like

Oh. I Recently, I read an interesting article on this topic. Perhaps this can help you find a solution: