How do you copy by value a composite data type?
Data types are used to store different kinds of variables.
Basically there are six data types which is divided into 3 categories:
Primitive data types: →Strings, Number & Boolean.
Composite data types: →Object, Array, Function(All these 3 are objects).
Special data types: →Undefined and Null.
Copy by value
In this, the data which is stored in the variable is passed to another variable. Both the variable points to two different memory location.
Above example, the contents of variable named “a” wont change even if we change the contents of variable “b”.
Copy by reference
Composite data types are copied by reference.
Here change in data of variable “b” will lead to change in data of the original variable that is the variable “a” ,that is both the orginal variable and copied variable points to same memory location.
So, how can we copy by value a composite datatypes?
There are 3 ways to copy by value for composite data types.
- Using the spread (
- Using the
- Using the
- Using Array.map().
It is mostly used in the variable array where there is more than 1 values are expected. It allows us the privilege to obtain a list of parameters from an array. Using spread will clone your object that will be a shallow copy.
Object.assign() method copies all elements own properties from one or more source objects to a target object. Note the empty  as the first argument, this will ensure you don’t mutate the original object.
3. Using JSON.stringify() and
This method is normally used to return a subset of the elements, starting at a specific index and optionally ending at a specific index of the original array. When using
array.slice()you will end up with a copy of the original array.
This methods will return a new array with all (or some) values of the original one. While doing that, you can also modify the values.