DEV Community

João Juliasz de Morais
João Juliasz de Morais

Posted on

Shallow copy and Deep copy in JavaScript

An important concept to know as a javascript developer is the difference between shallow copy and deep copy.
First, let's talk how object works in javascript.

An object is a dynamic data type that can take in collections of key-value pairs, where each key corresponds to a property and each value represents the property's associated data.
Objects can hold various data types, including numbers, string, booleans, array, other objects, and even functions.

Shallow copy

A shallow copy of an object is a copy whose properties share the same references as those of the source object from which the copy was made. In simple words, both objects point to the same address in memory. So, when you change either source, or the copy, you may cause changes in the other object too.

const sourceObj = {name: "Jane", surname: "Doe"}
const copyObj = sourceObj

copyObj.name = "Joe"

console.log(sourceObj) // {name: "Joe", surname: "Doe"}
Enter fullscreen mode Exit fullscreen mode

Deep copy

On the other hand, a deep copy is a copy whose properties do not share the same references as those of the source object from which the copy was made. So, all the properties from the source object will be in the copy object, but the new object will be pointed to a different address in memory. In this way, both objects are independent of each other in case of modification. In Javascript we can use JSON.parse() and JSON.stringify() methods.

const sourceObj = {name: "Jane", surname: "Doe"}
const copyObj = JSON.parse(JSON.stringify(sourceObj))

copyObj.name = "Joe"

console.log(sourceObj) // {name: "Jane", surname: "Doe"}
console.log(copyObj) // {name: "Joe", surname: "Doe"}
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

A better way is to use the native structuredClone function. It's faster and doesn't have any of the problems with the methods above. Read more about it here.

Collapse
 
joao_juliasz profile image
João Juliasz de Morais

Thanks for your comment Jon.
The structuredClone is a good option also. The only thing to have attention is the node version, it must be >= 17.0.29
Check it here.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

This is the first time you mention Node at all