DEV Community

Muhammad Asif
Muhammad Asif

Posted on

Deep Copying in JavaScript just in few minutes

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);
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode
let b = [...a]
Enter fullscreen mode Exit fullscreen mode
b[1] = 4
Enter fullscreen mode Exit fullscreen mode
console.log(b[1]) // 4
Enter fullscreen mode Exit fullscreen mode
console.log(a[1]) // 2
Enter fullscreen mode Exit fullscreen mode

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

Support

Buy me a Coffee

Top comments (2)

Collapse
 
ll profile image
Lorenzo Lomartire

To deep copy an object I prefer using:
var deepcopy = {...original, ...JSON.parse(JSON.stringify(original))};
because it copies also methods, not only properties.

Collapse
 
muhammad_asif profile image
Muhammad Asif

well said