In Programming, understanding "Shallow copy" and "Deep copy" is very important. Most probably you will get this question in Frontend Engineering Interviews. One should understand this as we will be playing with data mostly.
Let's see what these two copy means in detail with working examples.
What is Shallow Copy?
Shallow Copy is also identified as "Pass by Reference".
When we create a shallow copy, we create a new copy that is connected to the original element.
So when you change the original element it will also affect the copied element, and vice versa.
What is Deep Copy?
Deep Copy is also identified as "Pass by Value".
When you create a deep copy, you make an identical copy of the original and its properties.
These properties are not connected, so If you change the original, that change will not affect the copied element.
Note: Spread Operators do not deep copy nested objects.
Wait, but how one could identify if it is a deep copy or shallow copy?
Primitive types: (Deep Copy)
- All Primitive types like numbers, strings, and boolean, etc. are deep copied which means that the copied element and the original are not connected.
Non-primitive types: (Shallow Copy)