Differentiate between shallow copy, normal copy, and deep copy in javascript

1. Shallow Copy:

  • Description: A shallow copy is a copy of the object where the fields of the object are copied, but the referenced objects are not. Only the memory addresses of referenced objects are copied.
  • Techniques:
  • Using the spread operator: {...originalObject} for objects, [...originalArray] for arrays.
  • Object.assign({}, originalObject) for objects.
  • Limitation: If the original object has nested objects, the nested objects are shared between the original and the shallow copy. Modifying the nested object in one will affect the other.

2. Normal Copy (Assignment):
* Description: When you assign one object to another using the assignment operator (=), you’re just copying the reference to the object, not the actual object itself.
* Example: let obj2 = obj1;
* Limitation: Both variables refer to the same object. Changes to one will reflect in the other.

3. Deep Copy:
* Description: A deep copy is a copy where the original and the copied objects don’t share any references. Nested objects are recursively copied.
* Techniques:
* JSON.parse(JSON.stringify(originalObject)): This is a quick way to achieve a deep copy, but it has limitations, e.g., it doesn’t work with functions, undefined, or special objects like RegEx, Map, Set, etc.
* Libraries like Lodash have a cloneDeep method that can create a deep copy: _.cloneDeep(originalObject).
* Advantage: The copied object is independent of the original object, including all nested objects and arrays.