Ratan Deep Singh
2 min readNov 4, 2020

--

How to copy by value a composite data type

Hello everybody,
This blog is to explain about copy by value, copy by reference and how to copy by value a composite data type.

Copy by value:

This usually applies to primitive data types (i.e. number, boolean and string)
Lets have a look at an example about this.

In the above example, we have assigned 10 to variable a and then a to variable b.
Since both of these variables are primitive data types, both variables points towards different memory location i.e., it has a copy of its own.
It means, change in value of variable b doesn’t affect the value of variable a.

Copy by reference:

This usually applies to composite data types (i.e. array, object and function).
Lets have a look at an example about this.

In the above example, we have assigned value [1,2,3] to array arr1 and assigned array arr1 to array arr2.
So, here change in value of array arr2 affects array arr1 as both points towards same memory location.
Hence, both the arrays prints the [1,2,3,4] after pushing the 4 to array arr2

Copy by value a composite data type.

What changes do we make to our code, so that changes in one array doesn’t affect second array.

We can use the concept of SPREAD OPERATOR ( … ) to overcome this.
To have a better understanding, let’s look at below example.

So, arr2 makes a copy of its own in the form of […arr1].
What […arr1] does here is, it takes in an array arr1 and expands it into individual elements, and again it takes the form of array and gets assigned to arr2.

So, the arr1 doesn’t get altered even after we make changes to array arr2, after the usage of spread operator.

Hope, you guys found it useful.

--

--