❌You Don't Know How JavaScript Copy Variables (Shallow Copy)
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 copy
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 copy
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
When you create these values, they are tightly coupled with the variable they are assigned to. They only exist once. That means you do not really have to worry about copying primitive data types in JavaScript. When you make a copy, it will be a real copy.
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.
With Object
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:
Shallow copy
Deep copy
Making deep copies without thinking
With Arrays
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:
Conclusion
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!
Reference
https://www.freecodecamp.org/news/copying-stuff-in-javascript-how-to-differentiate-between-deep-and-shallow-copies-b6d8c1ef09cd/
https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy