Why there is a difference in behaviour for copying contents in the primitive and non-primitive type
JavaScript supports eight data types. Booleans, Null, Undefined, Number, BigInt, String, Symbol are primitive values except for object references.
Many common data types such as arrays, functions, and dates are object references under the hood.
Primitive values are stored in variables directly. where Objects, on the other hand, are stored as references. A variable that has been assigned an object will not store that object directly, it stores the memory address of the location that the object exists at.
This is like how a street address does not contain all information of a particular residence, it contains the details of where the residence is located geographically.
Consider a non-primitive data type ie, an array arr. we are assigning arr to arr2, another array and if we modify arr2 array, arr array also affects because by assigning arr2=arr, arr2 array is pointing to memory where arr array is pointed, so it will affect arr array if we change arr2 array. (we are using one memory location where arr and arr2 are pointing).
The main difference is where they stay in the memory, objects are stored in the heap while value type is stored directly in the Stack.
heap : is an area of memory used for dynamic memory allocation.
stack : is the section of memory that is allocated for automatic variables within functions. Data is stored in the stack using the Last In First Out (LIFO) method.
Primitive values are immutable — they cannot be changed after being created. Object references, however, are mutable and can be changed.
Since objects are stored as references, special care must be taken when duplicating objects and when performing equality checks on objects.