Shallow copies share nested data, so changes in one reflect in the other. Deep copies create independent duplicates. Object.assign makes shallow copies of nested objects, while structuredClone ensures a true deep copy. Essential for avoiding unexpected side effects!
When working with objects in JavaScript, it's crucial to understand the difference between deep and shallow copies. A shallow copy creates a new object, but instead of copying nested objects, it copies references to them. This means if you modify a nested object in the copy, the original object will also be affected.
In contrast, a deep copy creates a completely independent clone of the original object, including all nested objects. Modifications to the deep copy will not impact the original object.
Object.assign() is a commonly used method for copying object properties. While it's often thought of as a way to create a deep clone, it has a significant limitation: it only performs a deep clone for the first level of properties. If your object contains nested objects (sub-properties), Object.assign() will only create a shallow copy of these nested structures.
Let's illustrate this with an example, as discussed in the provided transcript:
In this example:
•age property: When newUser.age is changed to 20, the user.age remains 30. This demonstrates that Object.assign() created a deep clone for the age property, as it's a direct property of the user object.
•address.city property: However, when newUser.address.city is changed to Gurugram, the user.address.city also becomes Gurugram. This is because address is a nested object, and Object.assign() only copied its reference, not its value. Therefore, changes to the address object in newUser are reflected in the original user object.
To create a true deep clone in JavaScript, especially when dealing with nested objects, you need alternative methods. One modern and efficient approach is the structuredClone() method.
As seen above, using structuredClone() ensures that all nested properties are also deeply copied, providing a completely independent clone of the original object. There are other methods as well, such as using JSON.parse(JSON.stringify(object)) (with its own limitations for certain data types like functions or undefined), or custom recursive cloning functions.
Average 4.7 by 3 learners