Why There Is a Difference In Behaviour For Copying Contents In Primitive and Non Primitive Data Type?

To understand this, first we have know the difference between primitive and non-primitive data types.

Primitive Data types

Data types such as number, strings, Boolean, undefined, null are called primitive data types in Java Script. These data types hold small values and the values of the elements are copied by value.

Composite Data Types

Data types such as objects, arrays, functions are called composite data types in Java Script. These data types are capable of holding large values and the values of the elements are copied by reference.

So now arises a question, Why there is difference in behaviour of copying between these two data types?

This all depends on how the data is stored in the memory location. Now we know that primitive data types hold less data than composite types. Hence the values from primitive and composite data types are stored in two different types of memory called as Stack and Heap. In Stack, memory is allocated in a contiguous block and the values are retrieved based on first in last out bases and the data retrieval rate is fast. In Heap more data can be stored but in random order and the data retrieval rate is slower than Stack.

Fig(1)

So, for primitive values as they contain less data and are used quite often in a program these have to be accessed faster, hence these are stored in Stack. As composite datatypes hold lot more values than primitive once, so these values are stored in Heap but the address pointing to their memory location are actually stored in Stack to make the system more efficient, as shown in the fig (1) and fig (2)

Fig(2)