![]() |
VOOZH | about |
A shallow copy occurs when you copy the reference of an object to a new variable. In this process, only the top-level properties are copied, while nested objects or arrays still reference the original memory location. This means that if you change the nested properties in one object, those changes will reflect in the other because they share the same memory reference.
A shallow copy is created using methods like the spread operator ({ ...obj }) or Object.assign(). In contrast, using the assignment operator (=) only copies the reference, not the actual object:
Example: Below is an example of a shallow copy.
Note: Since this object contains only primitive values, modifying the shallow copy does not affect the original object. Shallow copy issues occur only when the object contains nested objects or arrays.
A deep copy, on the other hand, creates a completely independent copy of the object, including all nested objects or arrays. This ensures that changes made to one object do not affect the other. Each object is stored in a separate memory location, making them entirely independent.
Now to create a deep copy of an object in JavaScript we use JSON.parse() and JSON.stringify() methods. Let us take an example to understand it better.
Example: Below is the example of deep copy.
While the JSON approach is simple, it has its limitations:
Lodash is a JavaScript library that provides multiple utility functions and one of the most commonly used functions of the Lodash library is the cloneDeep() method. This method helps in the deep cloning of an object and also clones the non-serializable properties which were a limitation in the JSON.stringify() approach.
Output:
Explanation: Both objects have different properties after the modification. Also, the methods of each object are differently defined and produce different outputs.