Shallow Copy:
A
shallow copy of an
object refers to a new object that is created, duplicating the structure of the original object. This duplicate contains references to the same child objects as the original but not the actual child objects themselves. In other words, while the top-level properties of the object are copied, any nested objects or arrays within the original object are still referenced by both the original and the shallow copy.
To better understand the concept of a shallow copy, consider an example using JavaScript:
const originalObject = {
prop1: 'Hello',
prop2: {
nestedProp1: 'World'
}
};
// Creating a shallow copy
const shallowCopy = Object.assign({}, originalObject);
// Modifying the shallow copy
shallowCopy.prop1 = 'Hola';
shallowCopy.prop2.nestedProp1 = 'Mundo';
console.log(originalObject); // { prop1: 'Hello', prop2: { nestedProp1: 'Mundo' } }
console.log(shallowCopy); // { prop1: 'Hola', prop2: { nestedProp1: 'Mundo' } }
In this example, we create a
shallow copy of originalObject using Object.assign(). Both originalObject and shallowCopy have their top-level properties (like prop1) independently modified without affecting each other. However, when we modify a nested property (like nestedProp1) within shallowCopy, it also reflects the same change in originalObject. This is because both objects reference the same nested object
Deep copy:
For deep copy explanation, click
here