Copy by value for a Composite Data type in JavaScript

Mohammad Maaz
Nov 3, 2020

COPY BY VALUE FOR COMPOSITE DATATYPES CAN BE PERFORMED WITH THE HELP OF SPREAD OPERATOR.[…].

REFER BELOW FOR CLEAR EXPLANATION WITH EXAMPLE.

Arrays and Objects can be classified as a composite data type in JavaScript.

Composite datatypes also known as nonprimitive datatypes are passed by reference, where as primitive datatypes like integer, string are passed by value.

PASS BY VALUE FOR PRIMITIVE DATATYPE:

In the above example when a is assigned to b ,copy of ‘a’ is created for b and if we are changing value of a, value of b is not affected because already another copy of a is created and stored for b.

PASSBYREFERENCE FOR COMPOSITE DATATYPE:

In the above example, for arrays, we have assigned arr array to arr2 and we are trying to modify arr2 array, arr array also affects because while assigning arr2=arr, we are actually not creating a copy of arr array, arr2 array is pointing to memory where arr array is pointing, so it affects arr array if we change arr2 array.(we have only one memory location where arr and arr2 are pointing).

How to overcome above problem in composite types?

This can be achieved with the help of spread operator (…). in javascript.

In the above example we used spread operator for arr array, in this way it creates a copy of arr array and arr2 points to that copy, so if we are trying to change arr2 array, it doesnot affect arr array, because now we have two different copies of arrays.

--

--

Mohammad Maaz
0 Followers

Software Developer who aspires to add a value to society