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

Kashish Yadav
2 min readNov 15, 2020

In JavaScript, the data types are categorized into three main types- 1.Primitive

2. Trivial

3. Composite

The primitive data types are Numbers, BigInt, Boolean and String. The trivial data types include “null” and “undefined”, whereas the composite data types involve “objects” such as arrays, methods/functions, etc.

The primitive data types when copied to another variable, support “copy by value” whereas non-primitive data types (objects) when copied to another variable, support “copy by reference”.

Copy by value (deep copy)- If a primitive type is assigned to another variable, that variable now is said to contain primitive value.

For example:

var x = 10;
var y = ‘abc’;

x contains 10 and y contains ‘abc.

When we assign these variables to other variables using ‘=’, we copy the value to the new variable. Therefore they are copied by value. In the code below, variable “b” is assigned y’s value. When you log all the variables to the console, you get the below result. However, it should be noted that these exist as separate variables and that just the values are copied. These variables in no way are related to each other, they simply carry the same values.

var x = 10;
var y = 'abc';var a = x;
var b = y;console.log(x, y, a, b); // -> 10, 'abc', 10, 'abc'

Copy by reference (shallow copy)- When an object, such as an array, is copied to another variable using the assignment operator “=, the address of the object is what’s copied over as if it were a primitive type, instead of the actual value. This is why objects are normally known to copied by reference than value.

The behaviors of deep and shallow copies differ in terms of memory allotment. Deep copy allots memory to the variable that carries a primitive’s value. While, shallow copy simply points to the address of the original object when copied to another variable. No new memory is allotted in case of shallow copy so it saves up on a considerable amount of memory that would otherwise be unnecessarily used up by deep copying.

Thank you for reading! :)

--

--