In the previous Article, I have written about
Shallow Copying in javascript using Spread Operator
You can check it out!!
Deep Copy
Unlike the shallow copy, deep copy makes a copy of all the members of the old object, allocates separate memory location for the new object and then assigns the copied members to the new object. In this way, both the objects are independent of each other and in case of any modification to either one the other is not affected. Also, if one of the objects is deleted the other still remains in the memory. Now to create a deep copy of an object in JavaScript we use JSON.parse()
and JSON.stringify()
methods. Let us take an example to understand it better.
Code Implementation:
var employee = {
eid: "E102",
ename: "Jack",
eaddress: "New York",
salary: 50000
}
console.log("=========Deep Copy========");
var newEmployee = JSON.parse(JSON.stringify(employee));
console.log("Employee=> ", employee);
console.log("New Employee=> ", newEmployee);
console.log("---------After modification---------");
newEmployee.ename = "Beck";
newEmployee.salary = 70000;
console.log("Employee=> ", employee);
console.log("New Employee=> ", newEmployee);
Copy from Array:
Copying arrays is just as common as copying objects. A lot of the logic behind it is similar, since arrays are also just objects under the hood.
Nested Arrays:
Similar to objects, using the methods above to copy an array with another array or object inside will generate a shallow copy. To prevent that, also use JSON.parse(JSON.stringify(someArray))
Spread Operator:
const a = [1, 2, 3]
let b = [...a]
b[1] = 4
console.log(b[1]) // 4
console.log(a[1]) // 2
To deal with objects and arrays that are referenced inside of your instance, you would have to apply your newly learned skills about deep copying!
With that copy method, you can put as many values as you want in your constructor, without having to manually copy everything!
Wrapping Up
I hope you enjoyed the article, if yes then don't forget to press ❤️ and Subscribe. You can also bookmark it for later use. It was fun to create this article and If you have any queries or suggestions don't hesitate to drop them. See you.
You can extend your support by giving me stars on GitHub Profile.😊👇
Github
Portfolio
Top comments (2)
To deep copy an object I prefer using:
var deepcopy = {...original, ...JSON.parse(JSON.stringify(original))};
because it copies also methods, not only properties.
well said