All Articles

Primitive types Vs Reference types in JavaScript

The JavaScript language has 7 data types. They are,

  • Numbers
  • Strings
  • Boolean
  • Object
  • Null
  • Undefined
  • Symbol[New in ES6]

Based on the storing of data, these data types are classified into two: primitive and reference. The types undefined, null, boolean, number, string, and symbol comes under primitive types and object (array/function) comes under reference types.

The main difference between these two are, Primitive types are stores directly, Reference types reference to an address. Sometimes it is very confusing. Let’s clear with examples.

Primitive types

let color1 = "black";
let color2 = color1;
color1 = "green";

Both color1 and color2 are different. That means the original value was not changed, we can only change the copy. Because both values are stored as different slots in memory (Stack memory).


Reference types

For large things like array or object, the primitive types don’t work (Memory size issues). Because the contents of type can not fit in the memory. So reference types use Heap memory.

let numbers1 = [1, 2, 3];

let numbers2 = numbers1;


Here we are pushing the element to numbers2 array. But the numbers1 array also changed, since the memory reference got copied. It means both arrays point to the same address.

It means it refers to a slot in memory somewhere else (Heap memory). Unlike the primitive value, when you manipulate an object, you are working on the reference to that object, rather than the actual object. In short, a variable that stores an object is accessed by reference.