The spread operator in JavaScript is a convenient way to make copies of objects. But there is one catch. If the object contains nested data, then the spread operator creates deep copies of the outermost data and shallow copies of the nested data.
In a deep copy, the value is copied. A brand new object/value is cloned. In contrast, shallow copy involves copying the reference addresses, due to which changing one object/value alters the other object/value. You can observe this in the code snippet image.
So to create deep copies of nested objects, we can stringify the objects using JSON.stringify() and then parse them JSON.parse(). This results in creating a deep copy of an object containing nested data.
credit: Rabi Siddique
Top comments (0)