DEV Community

khaitd
khaitd

Posted on

Deep copy Vs Shallow copy

When assigning values to variables it is handy to be able to able to make a copy of an existing variable. In order to avoid modifying any existing data it is important to know that there are different types of copies, and when to use each.

Image description

Making a copy means creating a new variable and assigning it the same values as the copied variable. But there is an important concept to consider, do you want to make a deep or a shallow copy? Both copies contain the same values, but deep copies have their own space in memory while shallow copies point to the same space as the original variable. The consequence of this is that any modifications made to a shallow copy will affect the original, but any modification made to a deep copy are independent of the original variable.

There are multiple ways to make copies of objects such as using a spread operator, assignment, etc.

When making copies make sure to take into consideration whether your clone will cause unwanted changes to the original.

Image description

Top comments (2)

Collapse
 
jvictor940 profile image
Jvictor940

Great Read!

Collapse
 
rusty619 profile image
Ruslan Khait

sick naruto reference