Why primitive data types are copied by value and non primitive data types by reference in javascript?

Vinay Chaturvedi
2 min readNov 2, 2020

JavaScript has 6 primitive data types: String, Number, Boolean, Null, Undefined, Symbol (new in ES6). A variable can hold one of two value types: primitive values or reference values. Reference values store the non-primitive data types like arrays and objects. Whenever we copy a primitive value holding variable to a new variable using the ‘=’ assignment operator, it is copied by value, that is the new variable holds the copy of the old variable. But, on the other hand, whenver we copy a non-primitive reference variable to a new variable using the ‘=’ assignment operator, it is copied by reference, meaning the new variable isn’t a copy of the old variable, instead, it is another reference or name to the value inside. So, if we modify the old variable in the latter case, the new variable shall also have it’s value updated and vice versa.

That is copy by value in case of primitive values and copy by reference in case of non-primitive values. This happens because:

Primitive values are data that are stored on the stack and thus a primitive value is stored directly in the location that the variable accesses. Whereas, reference values are objects that are stored in the heap, and thus a reference value stored in the variable location is a pointer to a location in memory where the object is stored. Thus, when we assign the value of a primitive to another variable, a new copy of the value is made in memory because of the stack. On the other hand, when we make assign a non-primitve, reference value to a variable, a new reference is created to the original value because of the heap strucuture.

--

--