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

Santosh Kumar Divate
2 min readNov 5, 2020

--

In JavaScript, a variable may store two types of values: primitive and non primitive types. JavaScript provides primitive types as undefined, null, boolean, number, string, and symbol, and non primitive(reference) types as objects, arrays, and functions.

The size of a primitive value is fixed, therefore, JavaScript stores the primitive value on the stack.

Whereas the size of a reference value is dynamic so JavaScript stores the reference value on the heap. Since these types do not have a fixed size, their values cannot be stored directly in the fixed bytes of memory associated with each variable. Instead, the variable stores a reference to the value which is efficient in storage. This reference is some form of pointer or memory address. It is not the data value itself, but it tells the variable where to look to find the value.

When you assign a value to a variable, the JavaScript engine will determine whether the value is a primitive or reference value. If the value is a primitive value, when you access the variable, you manipulate the actual value stored in that variable. In other words, the variable that stores a primitive value is accessed by value. Unlike a primitive value, when you manipulate an object, you work on the reference of that object, rather than the actual object. It means a variable that stores an object is accessed by reference.

So when you copy a primitive data from one variable to the other you are copying its value in to the new variable where both are independent of each other. Whereas for the reference type you are copying the reference of the reference type instead of the value in the object and thus both the variables are pointing to the same reference which are dependent to each other.

There is one unusual case where string can behave like a primitive type or a reference type. Strings have variable size, so they cannot be stored directly in fixed-size variables which lets us think like it is a reference type. On the other hand, strings behave like a primitive type as strings are immutable: there is no way to change the contents of a string value. This means that we cannot construct an example like the one where arrays are copied by reference. In the end, it is a matter of debate whether you think of strings as an immutable reference type that behaves like a primitive type or as a primitive type implemented with the efficiency of a reference type.

--

--