Issue during my work
script
Here is part of my script. Can you find where the problem is:
const args = process.argv.slice(2) |
output
Name this js file as test.js and run at node test.js command.
Then you can Console log as followed:
[ |
From the output, we can see a strange phenomenon that during one single assignment, the whole ‘id’ column of data is assigned.
Why it happens
Shallow Copy:
- When a reference variable is copied into a new reference variable using the assignment operator, a shallow copy of the referenced object is created. In simple words, a reference variable mainly stores the address of the object it refers to. When a new reference variable is assigned the value of the old reference variable, the address stored in the old reference variable is copied into the new one.
- This means both the old and new reference variable point to the same object in memory. As a result if the state of the object changes through any of the reference variables it is reflected for both.
From the above example, it is seen that the newly created object has the same memory address as the old one. Hence, any change made to either of them changes the attributes for both. If one of them is removed from memory, the other one ceases to exist. In a way the two objects are interdependent.
How to solve
Deep Copy:
- Unlike the shallow copy, deep copy makes a copy of all the members of the old object, allocates separate memory location for the new object and then assigns the copied members to the new object.
- In this way, both the objects are independent of each other and in case of any modification to either one the other is not affected. Also, if one of the objects is deleted the other still remains in the memory.
To overcome this problem, deep copy should be used.
script fixed
So I fixed my script like that:
// deep copy |
correct output
Now, the output becomes correct.
[ |