How do you copy by value a composite data type?

Namrata Dwivedi
2 min readDec 3, 2020

We use data types to specify what kind of data can be stored & manipulated within a program.

In Javascript, the data types can be classified into 3 major categories as:

  1. Primitive (pass by value)
  2. Trivial
  3. Composite (pass by reference)

Primitive data types

String, Boolean and Number are primitive data types.

Primitive data type example illustration

From the above code snippet, we infer that “Primitive data types can hold only one value at a time.” In the above example when a is assigned to b, copy of a is created for b and if we are changing the value of a, the value of b is not affected because already another copy of a is created and stored for b.

Composite Data Types (pass by reference)

Objects, Array and Function (which are all types of objects) are composite data types.

Composite data type example

“Composite data types can hold collections of values and more complex entities.” Variables that are assigned a non-primitive value are given a reference to that value. That reference points to the object’s location in memory. The variables don’t actually contain the value.

Trivial Data Types

‘Undefined’ and ‘Null’ are trivial data types.

Trivial data type example

The undefined data type can only have one value-the special value undefined. If a variable has been declared but has not been assigned a value, has the value undefined.

A null value means that there is no value. It is not equivalent to an empty string (“”) or 0, it is simply nothing.

How to Copy by value a composite data type?

Copy by value a composite type can be achieved with the help of spread operator ().

Copy by value example for Composite Data Type

Spread operator 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.

#JavascriptTips #Javascript

--

--