Shallow copy vs deep copy js

{Imagine two objects: A and B of same type _t(with respect to C++) and you are thinking about shallow/deep copying A to B}

Shallow Copy: Simply makes a copy of the reference to A into B. Think about it as a copy of A's Address. So, the addresses of A and B will be the same i.e. they will be pointing to the same memory location i.e. data contents.

Deep copy: Simply makes a copy of all the members of A, allocates memory in a different location for B and then assigns the copied members to B to achieve deep copy. In this way, if A becomes non-existant B is still valid in the memory. The correct term to use would be cloning, where you know that they both are totally the same, but yet different (i.e. stored as two different entities in the memory space). You can also provide your clone wrapper where you can decide via inclusion/exclusion list which properties to select during deep copy. This is quite a common practice when you create APIs.

You can choose to do a Shallow Copy ONLY_IF you understand the stakes involved. When you have enormous number of pointers to deal with in C++ or C, doing a shallow copy of an object is REALLY a bad idea.

EXAMPLE_OF_DEEP COPY_ An example is, when you are trying to do image processing and object recognition you need to mask "Irrelevant and Repetitive Motion" out of your processing areas. If you are using image pointers, then you might have the specification to save those mask images. NOW... if you do a shallow copy of the image, when the pointer references are KILLED from the stack, you lost the reference and its copy i.e. there will be a runtime error of access violation at some point. In this case, what you need is a deep copy of your image by CLONING it. In this way you can retrieve the masks in case you need them in the future.

EXAMPLE_OF_SHALLOW_COPY I am not extremely knowledgeable compared to the users in StackOverflow so feel free to delete this part and put a good example if you can clarify. But I really think it is not a good idea to do shallow copy if you know that your program is gonna run for an infinite period of time i.e. continuous "push-pop" operation over the stack with function calls. If you are demonstrating something to an amateur or novice person (e.g. C/C++ tutorial stuff) then it is probably okay. But if you are running an application such as surveillance and detection system, or Sonar Tracking System, you are not supposed to keep shallow copying your objects around because it will kill your program sooner or later.

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 vs deep copy js

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:

Shallow copy vs deep copy js

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 vs deep copy js

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;

Shallow copy vs deep copy js

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:

Shallow copy vs deep copy js

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”:

Shallow copy vs deep copy js

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:

Shallow copy vs deep copy js

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.

What is difference between shallow copy and deep copy in JavaScript?

A deep copy means that all of the values of the new variable are copied and disconnected from the original variable. A shallow copy means that certain (sub-)values are still connected to the original variable. To really understand copying, you have to get into how JavaScript stores values.

What is the difference between a deep copy and a shallow copy?

Shallow Copy stores the copy of the original object and points the references to the objects. Deep copy stores the copy of the original object and recursively copies the objects as well. Shallow copy is faster. Deep copy is comparatively slower.

What is a shallow copy in JavaScript?

A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made.

What is drawback of shallow copy?

The problem with the shallow copy is that the two objects are not independent. If you modify the one object, the change will be reflected in the other object. A deep copy is a fully independent copy of an object. If we copied our object, we would copy the entire object structure.