Shallow Copy and Deep Copy in JavaScript

 In JavaScript, there are two ways to copy objects: Shallow copy and Deep copy

Shallow copy

Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

In other words, it copies the object and all its properties, but any nested objects or arrays will still reference the same memory location as the original object. It means that if you make changes to the nested object, it will also affect the original object, as well as the copied object.

Example:
const originalObject = { a: 1, b: { c: 2 } };
const shallowCopy = { ...originalObject };


Deep copy

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. 

In other words,  a deep copy is a copy that creates a new object with new memory locations for all of its properties and nested objects or arrays. It means that if you make changes to the copied object or any of its nested objects or arrays, it will not affect the original object.

Example:
const originalObject = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(originalObject));


Try it


Performance Considerations

It is important to note that deep copying can be more expensive in terms of performance than shallow copying. It is because creating a new object and copying all of its properties and nested objects can take more time and memory than simply creating a new object with references to the same memory locations as the original object.

Conclusion

In JavaScript, there are two ways to copy objects: shallow copy and deep copy. 

  • Shallow copying creates a new object with references to the same memory locations as the original object, while deep copying creates a new object with new memory locations for all of its properties and nested objects or arrays. 
  • Shallow copying can be more efficient in terms of performance, but may result in unexpected behavior if changes to a copied object affect the original object. Deep copying ensures that changes to a copied object do not affect the original object, but may be more expensive in terms of performance. 
  • While using JSON.parse() and JSON.stringify() is an easy way to create a deep copy of an object, it may not work in all cases. If you need to create a deep copy of an object, using JSON.parse() and JSON.stringify() is an easy option. However, if the object being copied contains functions or circular references, a recursive deep copy function may be necessary.