
Copying objects with shallow and deep copies
Primitive values such as strings, and numbers are copied by value, whereas objects are copied by reference. What do we mean by this? The following code example will explain this practically:
let num1 = 10; let num2 = num1; num1 = 6; console.log(num2); //10
The value of num1 which is the number 10 is assigned to the variable num2. Which is why even after we change the value of num1 to the number 6, the value of num2 remains the same. It’s because we copied by value of num1 to num2 before re-assignment of variable num1 to 6.
What then does copy by reference mean? When we copy by reference, the memory address of an object is shared with another object. For example:
let num1 = { amount:10 } let num2 = num1; num1.amount = 6; console.log(num2);
Since the memory address of the two objects are the same, when we change the value of
the num1 amount key from the number 10 to 6, we are changing the value at the memory location. Therefore, the value of the amount key in the num2 object will also be the number 6, since it refers to the same memory address.
When copy over objects, we cannot simply just use the assignment = operator. There are
two ways of copying objects:
1. Shallow copying
2. Deep copying
Which gets us to the next point, what do these two terms mean?
Shallow copy
In a shallow copy, a new object is created which has the exact values as the source object.
Primitive values are copied by value whereas if a field is of a reference type (example an
array or another object) then the reference/memory address is copied over to the newly
created target object. In a shallow copy, the source object and target object share the
same memory address.
Deep copy
In a deep copy, all the values (primitive and reference types) are duplicated into a source
object and allocated new memory locations. Therefore, the memory address of the target
and source objects is different. Changing the source object after a deep copy will not
affect the target object.
Note
An important note to keep in mind is that in a deep copy, the source and target objects have different memory addresses and are not connected. Whereas, in a shallow copy the source and target objects share a memory address.
in the second example, num2 = {amount:6} NOT 6