How do you copy by value a composite data type?

durgesh siva
3 min readDec 3, 2020

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.

  1. Using the spread (...) operator
  2. Using the Object.assign() method
  3. Using the JSON.stringify() and JSON.parse() methods
  4. Using Slice() method in JavaScript.
  5. Using Array.map().

1.Spread()

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.

2.Object.assign() method

The 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 JSON.parse() methods

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 .

4.Slice() method

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.

5.Array.map().

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.

--

--