Clone object in Javascript

2 min read

Often times, we want to create copies of variables for different purposes. There can be two different kinds of copies created - Shallow copy and Deep copy. Let's go over the terminologies and related examples:

Shallow Copy

Shallow copying means it only copies the normal object values but nested values still use the reference to an original object. This means that modifications made in one place would affect both places.

There are two methods to do it. With Spread Operator (…) and Object.assign().

const obj = {a:10, b:20, c:{d:30}};
const shallowClone = {...obj};
obj.c.d = 34; // updates the d property value
console.log(obj); // {a:10,b:20,c:{d:34}}
console.log(shallowClone); // {a:10,b:20,c:{d:34}}

Deep Copy

Deep copy method creates a copy where the source and the copied variable reference are completely different. It means that modifications made in one place would only affect the variable where we are making a change.

if the objects/arrays are not nested, then we can achieve deep copy by using Spread (...) operator:

const first_person = {
  name: "Manel",
  age: 34,
}

const second_person = { ...first_person };

second_person.age = 35;

console.log(first_person.age); // output: 34
console.log(second_person.age); // output: 35

In case of nesting, the spread operator creates a shallow copy.

If the objects/arrays are nested, then we can achieve deep copy by using JSON.parse() and JSON.stringify()
const obj = {a:10, b:20, c:{d:30}};
const deepClone = JSON.parse(JSON.stringify(obj));
obj.c.d = 35;

// d value is changed
console.log(obj); // {a:10,b:20,c:{d:35}}

// d value remains unchanged because there is no reference
console.log(deepClone); // {a:10,b:20,c:{d:30}}

References: