How do you copy by value a composite data type?
Composite data types are a combination of primitives and other data types.
A composite data type in JavaScript has multiple values, which grouped together. It works the same as the object in the class.The object ,array and function are composite data types.
Let us first see what Copy by Value and Copy by Reference are with examples
Copy by value is where the value is copied to another variable and any changes made to the value does not reflect in the original variable’s value.This is typically used for Primitive Data Types.
For Example:
In the above figure (Figure 1),the value of variable a remains the same despite the change in value to the second variable b.
However for composite data types Copy by Reference is performed,that is where both objects point to the same memory address
In the above figure(Figure 2),the change made in array brr is reflected in array arr and this is because both arrays are pointing to the same memory address.(Call by Reference).
Copy by value for a Composite Data Type
To Copy by Value for a Composite Data Type ,the Spread Operator(…) is used ,which is known as shallow copy.
In the above figure(Figure 3),the first array arr is not affected even though changes are made to the array brr .This is because the spread operator is used when assigning the array arr to the array brr.