JavaScript

Shallow Copy vs Deep Copy in JavaScript

The copying task in JavaScript is quite straightforward for primitive data types. However, you must carefully choose between the Shallow and Deep Copy techniques while handling objects and references.

In shallow copy only reference addresses are copied; therefore, altering one object will also apply the same changes to another object. To avoid such a situation, you can utilize the Deep copy procedure.

This post will explain the concept of Shallow Copy and Deep Copy using appropriate examples. So, let’s start!

Shallow Copy in JavaScript

A mechanism in which an object is bit-wise copied to a specified object is known as Shallow Copy.

  • The shallow copy method pastes an exact copy of a particular object into another object.
  • It is primarily utilized for copying One Dimensional array elements, where it only copies the elements present at the first level.
  • It only copies the reference addresses to another object.

Methods to Shallow Copy an Object in JavaScript

To shallow Copy a JavaScript object into another object, you can use the following methods:

  • Object.assign() method
  • spread operator […]
  • Assignment operator “=”

Note: If you utilize the “spread operator” or “Object.assign()” method, then after shallow copying, the copied object gets disconnected from the original object, whereas, in the case of using the “assignment” operator, altering the copied object will also modify the original object.

We will briefly discuss each of the mentioned methods to shallow copy an object in JavaScript.

Shallow Copy an object in JavaScript using spread operator

The “spread” operator can be utilized for shallow copying an object. It is represented as three consecutive dots “…”.

Syntax of using spread operator to Shallow Copy an object in JavaScript

let object2= {...object1};

Here, the spread operator will copy the key-value pair of “object1” to “object2”.

Example: Shallow Copy an object in JavaScript using spread operator

First of all, we will create an object named “employee” having two key-value pairs:

const employee= {   

 name: 'Alex',

 designation: 'Manager'

};

Then, we will shallow copy the “employee” object to the newly created “emp1” object using the spread operator:

let emp1= {...employee};

Additionally, you can verify if modifying the property values of the “emp1” object can also affect the “employee” object’s name property:

emp1.name = 'Max';

console.log(“emp1 name: ” + emp1.name);

console.log(“employee name: ” + employee.name); [/cc]

We have successfully copied the “employee” object to the “emp1” object and modifying the “emp1.name” property value have not applied any changes to the “employee.name” property:

Shallow Copy in JavaScript using Object.assign() method

The JavaScript “Object.assign()” method is utilized to shallow copy the “key-value” pair of an already created object into another object. The original object will not be affected while utilizing the object.assign() method.

Syntax of using Object.assign() method to Shallow Copy in JavaScript

Object.assign(target, source)

Here, “target” represents the JavaScript object whose key-value pair will be copied, and “source” indicates the object where the copied key-value pair will be placed.

Example: Shallow Copy in JavaScript using Object.assign() method

We will invoke the “Object.assign()” method for shallow copying the “employee” object to “emp1”:

let emp1 = { };Object.assign(emp1, employee);

The “Object.assign()” method will return the target object, which is “emp1” in our case:


Next, we will update the “emp.name” property value:

emp1.name = 'Stepheny';console.log("emp1 name: " + emp1.name);

console.log("employee.name: " + employee.name);

As you can see in the below-given output, altering the “emp.name” property value has not modified the “employee” object.

Shallow Copy in JavaScript using assignment operator

The assignment operator “=” can also assist in shallow copying an object in JavaScript. In the case of using the assignment operator, both of the variables will refer to the same object. Changes in one object will also affect the corresponding object’s property value:

Syntax of using assignment operator to Shallow Copy in JavaScript

object2 = object1

Here, the assignment operator copies the “object1” to “object2”.

Example: Shallow Copy in JavaScript using assignment operator

Now, we will use the JavaScript assignment operator for shallow copying the “employee” object to “emp1”:

let emp1 = { };emp1 = employee;

In the next step, we will specify “Stepheny” as the value of “emp1.name” property:

emp1.name = 'Stepheny';console.log("emp1 name: " + emp1.name);

console.log("employee.name: " + employee.name);

The given output signifies that changing the “emp.name” property value has not modified the “employee” object “name” property:


Now, we will discuss the concept of Deep Copy an object in JavaScript.

Deep Copy in JavaScript

Deep Copy” is a recursive procedure of copying object. This mechanism creates a new object and then clones the specified object’s key-value pair to it. This statement signifies that, while Deep Copying, a JavaScript object is completely cloned into another object. After that, the copied object gets disconnected from the original object.

Methods to Deep Copy an object in JavaScript

Methods utilized for deep copying a JavaScript object are JSON.stringify() and JSON.parse(),  where the stringify() method converts a particular JavaScript object to a string, and then the parse() method performs the parsing operation and returns an object.

Syntax of using JSON.stringify() and JSON.parse() methods to Deep Copy an object in JavaScript

let object2= JSON.parse(JSON.stringify(object1));

Here, the stringify() method converts JavaScript “object1” to a string, and then the parse() method performs the parsing operation and returns which will be stored in “object2”.

Example: Deep Copy  in JavaScript an object in JavaScript using JSON.stringify() and JSON.parse() methods

In this example, we have used the stringify() and parse() methods to copy “employee” to the “emp1” object. The “JSON.stringify()” method will convert the “employee” object into a “string” and then the “JSON.parse()” method parse the resultant string and return a JavaScript object:

let employee= { 

  name:'Alex',

  address: { city: 'Ankara', country: 'Turkey' }

 };

var emp1= JSON.parse(JSON.stringify(employee));

console.log(emp1);

Given output signifies that we have successfully copied the “employee” object to “emp1”:

Lastly, we will modify some properties of the “emp1” object and then check out the result:

emp1.name = 'Max';

emp1.address.city = 'Istanbul';

console.log("emp1.name: " + emp1.name);

console.log("emp1.address.city : " + emp1.address.city);

console.log("employee.name: " + employee.name);

console.log("employee.address.city : " + employee.address.city);

After performing the deep copying operation, the “emp1” gets disconnected from the “employee,” so any changes made in the “emp1” will not affect the “employee” object:


We have compiled all of the essential information related to Shallow Copy and Deep Copy objects in JavaScript. You can further explore it according to your requirements.

Conclusion

spread operator “[…]”, “Object.assign()”, and “assignment” operator are methods that permit you to shallow copy objects and to deep copy a JavaScript object, JSON.stringify() and JSON.parse() methods are used, where the JSON.stringify() method converts a particular object to a string, which is then parsed back using JSON.parse() method. This post explained the concept of Shallow and Deep Copy using appropriate examples.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.