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

Before knowing the difference between the behavior for copying contents in primitive and non primitive type, we have to know what is primitive and non primitive datatype.

Primitive datatype

In Java Script the data types like String, Number, BigInt, Boolean,Symbol are known as primitive datatype.

Non-Primitive datatype

It is usually referred as Object references, usually objects,functions and arrays are refered as non-primitive datatype.

Now get into the topic.

Behavior of copying content in Primitive and Non-primitive datatype.

Copying can be done in two ways they are

  • Copy by value.
  • Copy by reference.

Copy by value.

It is the process of copying the the values of the variables into the another variable.JavaScript always changing the value of the variable never changes the underlying primitive (String or number).

Copy by reference.

In the copy by reference method the values will get affected every time anywhere the value of variable changed which is passed as address for the function to perform operation.

Here the primitive datatype are mostly done by Copy by value.

For eg.

Copy by value

The non-primitive datatype are done by copy by reference

eg,

Here Obj.age acts as reference to the object age to copy the new value.

This is the behavior for copying contents in primitive and non primitive type.