Is possible to CALL BY VALUE for a COMPOSITE DATA TYPE in JavaScript? YES…

Myilvaganan Sakthivel
3 min readDec 12, 2020

What is a composite data type?

Composite data type is also known as non-primitive data type, it consisted of multiple values that are grouped together. Objects and Arrays are the two composite data types in Javascript.

Difference Between Primitive Data Type and Non-Primitive Data Type.

Primitive data types are passed in by value where Non-Primitive data types are passed in by reference.
Primitive data types are immutable data type was once created, the value can not be changed. Non- Primitive data types are mutable data types where the value can be changed after created.
Primitive data types are strings, numbers, null, undefined, and boolean. Non- primitive data types are arrays and objects.

Call by Value of Composite Data Type:

Example of Primitive Data Type (copy by value):

In the above image, the value of ‘a’ is assigned as 1 and ‘b’ is assigned as ‘a’, which means the value of ‘a’ is copied to ‘b’. Hence, the value of ‘a’ is not changed and here only the values are copied but not the memory or location of the variable. A separate memory is allocated to each variable ‘a’ and ‘b’.

Example of Non-Primitive or Reference or Composite Data Type (copy by reference):

Here, the ‘array1’ variable is stored data in array data type with multiple data types of strings, numbers, and bool. Then the ‘array2’ is assigned with ‘array1’ after a new element ”newly added string” is added using the push() function. But the output of both ‘array1’ and ‘array2’ are the same, therefore both variables are pointing towards the same memory or location for eg., 0x01. Because the variables are copied by reference but not by values.

Let us see how to copy by the value of non-primitive data types:

It can be possible using Spread Operator (…), three dots.?

Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

The spread operator used to copy by the value of the non-primitive data type.

In the above image, the ‘spreadarray2’ has the elements of ‘spreadarray1’ copied into it. Any changes made to ‘spreadarray1’ will not be reflected in ‘spreadarray2’ and vice versa.

In the same program, ‘spreadarray3’ which is copied as a reference had its value changed and the changes made in one array would reflect in the other array which in most cases is undesirable.

Hence with the help of Spread operator(…), we can copy by value for composite data types.

--

--