Why can't we just use "=" to copy objects? 😲
In JavaScript and Python, a reference to the original data is generated when they copy an object to a new variable rather than making a new copy of the object in memory.
Therefore, any changes made to the data affect both the original and modified data.
All Immutable data types have this problem
Solution: ✅
Luckily we can deep clone immutable data to save our lives! See the code snippet below.
Js:
We can use JSON.parse and JSON.stringify on the data we want to copy to create a new copy of it in memory.
Eg:
arr1 = [1, 2, 3]
arr2 = arr1 // Shallow clone
arr2.push(4)
console.log(arr1, arr2)
// op: [ 1, 2, 3, 4 ] [ 1, 2, 3, 4 ]
arr3 = JSON.parse(JSON.stringify(arr1)) // Deep clone
arr3.push(5)
console.log(arr1, arr3)
// op: [ 1, 2, 3, 4 ] [ 1, 2, 3, 4, 5 ]
- We can also use the spread operator specified in ES6, but it can clone only one level deep. Hence won't be suitable for multidimensional arrays for example.
const s1 = ['⭐', '⭐', '⭐'];
const s2 = ['⭐', '⭐', '⭐'];
const s3 = s1;
const s4 = [...s2];
s3.push(4)
s4.push(4)
console.log(s1, s2) // s1 is affected but not s2
// op: ['⭐', '⭐', '⭐', 4] ['⭐', '⭐', '⭐']
Py:
- We can use copy inbuilt module
import copy
a1 = [1, 2, 3, 4]
a2 = [1, 2, 3, 4]
b1 = a1
b2 = copy.deepcopy(a2)
b1.append(5) # shallow copy, a1 will also be modified
b2.append(5) # deep copy, a2 will not be modified
print(a1, a2)
# op: [1, 2, 3, 4, 5] [1, 2, 3, 4]
=================