DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Muhammad Saim Hashmi
Muhammad Saim Hashmi

Posted on

Normal vs Shallow vs Deep Copy in Javascript/Typescript

Hey everyone, just like my last article on Difference between ? and ?? in JavaScript/Typescript, I am motivated to write again to contribute something to the community. Today, we'll talk about how object copies work in Javascript/Typescript with code snippets.

Before starting, I would recommend you guys to look closely at this topic. Why? Because this thing causes a hell of a pain in the neck when dealing with Nested Objects. So let's get started.

Normal Copy

Normal copy does not copy the value, but its instance or its memory address. If the copied instance value is updated, the original value is updated. Similar to static keyword in Java(If you know Java).

Example

const original = { x: 0 }
const normalCopy = original;
normalCopy.x = 1; // also updates original.x
console.log(original.x); //prints 1
console.log(normalCopy.x); //prints 1
Enter fullscreen mode Exit fullscreen mode

Shallow Copy

Shallow copy copies the outermost object value and does not copy the nested objects. This means that the initial object values are copied while the nested ones are not copied by value but copied by reference.Ï

Example

const user = {
  name: "John",
  contact: {
    home: "+12345",
  }
}
const shallowCopy = { ...user };
shallowCopy.name = "John Smith";// updates its own copy
shallowCopy.contact.home = "+999";// updates both original and copy

console.log(user);
console.log(shallowCopy);
//Output
//https://dev-to-uploads.s3.amazonaws.com/uploads/articles/61n4uyvjpghid4kq0hdx.png
Enter fullscreen mode Exit fullscreen mode

Deep Copy

A deep copy copies the entire object with its nested objects and creates a new clone of it in the memory.

Example

const user = {
  name: "John",
  contact: {
    home: "+12345",
  }
}
const shallowCopy = JSON.parse(JSON.stringify(user));
shallowCopy.name = "John Smith";
shallowCopy.contact.home = "+999";

console.log(user);
console.log(shallowCopy);
//Output
//https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k7lb0jbhds7nzk8gwlkh.png
Enter fullscreen mode Exit fullscreen mode

Thanks for reading this article. Please do comment so that I can improve my content. Happy Monday.

Top comments (4)

Collapse
 
asadheidari profile image
AsadHeidari

excellent πŸ‘Œ

Collapse
 
saimwebhr profile image
Muhammad Saim Hashmi

Thanks mate :)

Collapse
 
abdulbasitmemon profile image
Abdul Basit Memon

Thanks for sharing :)

Collapse
 
saimwebhr profile image
Muhammad Saim Hashmi

Thanks Mentor :)

Hey 😍

Want to help the DEV Community feel more like a community?

Head over to the Welcome Thread and greet some new community members!

It only takes a minute of your time, and goes a long way!