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

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)
Fig(2)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store