Advertisement
There are two ways to copy an object,
Shallow Copy:
Shallow copy is a bitwise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.
Example
1var empDetails = {
2 name: "John",
3 age: 25,
4 expertise: "Software Developer",
5 };to create a duplicate
1var empDetailsShallowCopy = empDetails; //Shallow copying!if we change some property value in the duplicate one like this:
1empDetailsShallowCopy.name = "Johnson";The above statement will also change the name of empDetails, since we have a shallow copy. That means we're losing the original data as well.
Deep copy:
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.
Example
1var empDetails = {
2 name: "John",
3 age: 25,
4 expertise: "Software Developer",
5 };Create a deep copy by using the properties from the original object into new variable
1var empDetailsDeepCopy = {
2 name: empDetails.name,
3 age: empDetails.age,
4 expertise: empDetails.expertise,
5 };Now if you change empDetailsDeepCopy.name, it will only affect empDetailsDeepCopy & not empDetails
Advertisement
JavaScript Coding Exercise 3
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement