Understanding Javascript Primitives and References

Understanding Javascript Primitives and References

Learn the difference between primitive and reference data types in Javascript.

As a developer, they might ask if you understand the difference between primitive and reference data types. Primitive data types can store information as a slot in memory (memory address) while reference data types store a reference to a slot in memory.

Let’s have a closer look at javascript primitive and reference data types to understand it better.

Primitive data types

Primitive data types are booleans, numbers, strings, null, undefined, and symbols. When you set a variable with a primitive type the variable is that exact value. If you change the value, the variable simply becomes a new value.

When we write a primitive data type like this:

let colorOne = 'green';

On the call stack, the variable *colorOne* directly points to the value ‘green’.

Call Stack  
#000    colorOne -> | 'green' |  
#001                |         |

And if we change the value of the variable colorOne, the colorOne memory address #000 which holds the value green is directly changed to purple.

let colorOne = 'green',  
     colorOne = 'purple';

Reference data types

Reference data types are also known as complex types or container types. A reference data type can contain other values. Reference data types are arrays and objects. Since the contents of a reference data type cannot fit in the fixed amount of memory available for a variable, the in-memory value of a reference type is the reference itself (a memory address). The variable only knows the location of the object, not the object itself.

If we write a reference data type like this:

let color = {   
  primaryColor: 'green'  


let color = new Object();  
color.primaryColor = 'green';

Javascript will create the object in heap memory (a location in memory where memory may be allocated at random access) and store the memory address of the object in the color call stack location:

Call Stack       Heap  
#000    color -> | #101 |   #101 | primaryColor: 'green' |  
#001             |      |   #102 |                       |

Like you see the variable color doesn’t store the object directly but it points to the memory location (#101) of the object. Unlike primitive data types that hold their value directly. If you pass a reference data type around, you are merely passing the address of its memory location, not the actual value. Any change to the reference data type affects the memory it points to.


We have gone through the basics of javascript primitive and reference data types. This is an important topic because as a developer you should know the fundamentals of the language.

Thank you for reading & happy coding.

Did you find this article valuable?

Support Jeandre Melaria by becoming a sponsor. Any amount is appreciated!