How do you copy by value a composite data type| JAVASCRIPT
Data types are basically classified into three types
- primitive Data types
- non-primitive Data types (composite Data type)
- special Data types
In general primitive data types are passed in by value and composite data types are passed in by reference
Now, let’s see how a copy by value works in a primitive data type.
In the above image, the value of ” b” is copied to” c” as a value.We have also changed the value of “c” and it does not disturb the value of ”b” since “c” is set to a value of 20 and not reference/memory of “b” in case of primitive data type. A separate memory is allocated to each variable. This can also be called as shallow copy
Let’s see how the same thing works for a composite data type (array).
In the above image, we can clearly see that when we change the value in the “X” Array, “arr” is also changing. This is because the value of “arr” is initially stored in a memory, when we assign a value X=arr it goes to memory location copy the value as reference stores in X.
This happens because both are located in the same memory location.
How do we copy by value in a composite data type?
1) Using Spread Operator
One of the ways of copying the composite data type by value is achieved with the help of the spread operator (…).
In the above image, It is clearly seen that even though if we push a new value in ‘arr1’ it is not changed in ‘arr2’ because it is copied using spread operator[…]. If we observe ‘arr3’ is copied by reference method, so if arr1 is changed obviously arr2 is also getting changed.
2) Using Object.assign()
The Object.assign()
method copies all enumerable own properties from one or more source objects to a target object. It returns the target object. Note this will be a shallow copy.
3. Using JSON.parse() and JSON.stringify()
The JSON object, available in all modern browsers, has two useful methods to deal with JSON-formatted content: parse and stringify. JSON.parse() takes a JSON string and transforms it into a JavaScript object. JSON.stringify() takes a JavaScript object and transforms it into a JSON string.Using JSON.parse() and JSON.stringify() for copy performs deep copy .
The deep copy is a true copy for nested objects. Shallow copy copies only reference in case of nested objects.