What is Shallow Copy ? 🤔
Shallow Copy: When a reference variable is copied into a new reference variable using the assignment operator, a shallow copy of the referenced object is created. In simple words, a reference variable mainly stores the address of the object it refers to.
When a new reference variable is assigned the value of the old reference variable, the address stored in the old reference variable is copied into the new one. This means both the old and new reference variable point to the same object in memory.
As a result if the state of the object changes through any of the reference variables it is reflected for both. Let us take an example to understand it better.
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.
Primitive data types
Let’s see an example:
Reference data types
Technically, arrays are also objects, so they behave in the same way. I will go through both of them in detail later.
Here it gets more interesting. These values are actually stored just once when instantiated, and assigning a variable just creates a pointer (reference) to that value.
Create an object a with property test with value test1 and then copy
b = a and then change value test in object b .Let see example:
Making deep copies without thinking
Copying arrays is just as common as copying objects. You can use some ways for deep copy are Spread Operator, Array Functions, Nested Array.
Let see an example below:
In the end, you know should use the copy with reference data types for some case you want to copy an object or array split with original and some ways how to make a deep copy.
Thanks for reading. Please share your experiences, questions and feedback below!