Why there is a difference in behavior for copying contents in primitive and non-primitive types?

Ananth Astaputra
1 min readDec 4, 2020

In JavaScript, the data types are categorized into two main types-

1) Primitive

2) non-primitive (composite)

The primitive data types are Numbers, BigInt, Boolean and String. The trivial data types include “null” and “undefined”, whereas the composite data types involve “objects” such as arrays, methods/functions, etc.

Copy by value means the variable copies the value from the source and allocates different memory to it, So it doesn't disturb the value of the source variable. Whereas copy by reference in case of composite data type means it simply copies the address of source variable and then take reference from that variable. It is actually having the same memory allocated to the source variable and copied variable.

So in most of the cases, It is unnecessary that if a copied variable is changing the source variable also gets changed. So we use the spread operator […] and Object.assign method to make a shallow copy.

--

--

Ananth Astaputra
0 Followers

Enthusiastic in technological updates