A shallow copy means that only the top-level values (elements) are copied. If the array contains other arrays or objects inside it, the copy will still point to the same inner array or object.
let originalArray = [1, 2, [3, 4]];
// Creating a shallow copy using the spread operator
let shallowCopy = [...originalArray];
// Changing the inner array in the shallow copy
shallowCopy[2][0] = 99;
console.log(originalArray[2][0]); // Output: 99 (original array is also affected)
console.log(shallowCopy[2][0]); // Output: 99 (shallow copy is affected)
Explanation:
originalArray
and shallowCopy
point to the same inner array [3, 4]
.shallowCopy[2][0]
to 99
, it also changes originalArray[2][0]
, because both share the same inner array.A deep copy means that both the top-level and inner values (like objects or arrays inside the object) are copied. They are completely separate, so changes in the copy do not affect the original.
let originalObject = {
name: 'Shubhadip',
address: { city: 'Kolkata', zip: 700001 }
};
// Creating a deep copy using JSON methods
let deepCopy = JSON.parse(JSON.stringify(originalObject));
// Changing the inner object in the deep copy
deepCopy.address.city = 'Mumbai';
console.log(originalObject.address.city); // Output: 'Kolkata' (original is not affected)
console.log(deepCopy.address.city); // Output: 'Mumbai' (deep copy is changed)
Explanation:
originalObject
and deepCopy
are completely separate.deepCopy.address.city
to 'Mumbai' does not change originalObject.address.city
, because they are different objects in memory.