Shallow copy vs Deep copy
Copy to an object can be created in many ways in JavaScript. Let us first understand difference between primitives and non-primitives.
When we create a variable to hold primitive data, then that variables hold that data.
let data=200
When a variable is assigned with non-primitives like array or object, that variable holds reference to that non-primitive ,instead of that as value. This is very important point to notice when creating copy of an object.
Let us create a simple "student" object and its copy. To create copy we can use either Object.assign() or spread operator(...).
The above two objects will occupy different memory locations like below.
As of now, we are very clear with copying of objects.
Now ,let me add some non-primitives to student object like marks property with an array and address property with an object.
Here, the student object has two properties as references to other objects.(Array is also an object). The copy of student object(copyOfStudent) will get all properties , but , the properties marks and address will refer to same objects which are referred by student object ,instead of creating new copies of those. The following diagram illustrates that fact.
when we change the values of properties rollno,name and age, those changes will be reflected only in that object.But when change values of either marks or address, those changes will be reflected for both student and copyOfStudent objects. This is beacause, these two objects do not have separate copies of those two(marks array and address object).
This is called Shallow copy. It means ,copy of an object copies the ‘main’ object, but doesn’t copy the inner objects. The ‘inner objects’ are shared between the original object and its copy.
Deep copy
Unlike the shallow copy, a deep copy is a fully independent copy of an object. If we copied our student object, we would copy the entire object structure.
We can use a simple technique to achieve this.
Convert JavaScript object (student) to string.
For that, we can use JSON.stringify() method which takes JavaScript object as argument and returns its string representation.
Then, convert this string back to object using JSON.parse() method. Now, it takes complete string representation of object and produce a new object as a complete copy of all primitive and non-primitive values.
const copyOfStudent=JSON.parse(JSON.stringify(student))
You can see that, the copy object also has its own copy of all properties including primitives and non-primitives. This is called Deep copy.
Change the values in copy object(copyOfStudent) and compare main object(student) for better understanding.
Thanks for reading this article and hope you clear with the concept of shallow copy and deep copy