Primitive vs Reference Data Types in JavaScript

Mai Abdulhamid
Nov 25, 2023
2 min read
post_comment12 Comments
post_like12 Likes

In JavaScript, data types are split in two categories, and the computer treats each one differently. We haveprimitivedata types andreferencedata types.

#Primtive data types in JavaScript

They are numbers, strings, booleans, null, symbols, and undefined.

They are not objects, and do not have methods.

But you might be wondering about strings, because they do have methods. The fact is, JavaSvript converts primitive strings to string objects, so that it is possible to use string object methods.

How are primitive data types treated in JavaScript? When you declare a primitive data type in JavaScript, it is stored on a stack. A stack is a simple data structure that the computer uses to store and retrieve data quickly.

A primitive data type on the stack is identified by the variable name you used for declaration in your program. With each primitive data type you create, data is added to the stack.

    let numOne = 50;
    let numTwo = numOne; //numTwo=numOne=50
    numOne = 100;
    console.log(numOne); //outputs 100
    console.log(numTwo); //outputs 50

#Reference data types in JavaScript

Reference data types, unlike primitive data types, are dynamic in nature. That is, they do not have a fixed size.

Most of them are considered as objects, and therefore have methods. Examples of such data types include arrays, functions, collections, and all other types of objects.

#What's the difference between primitive and reference data types?

The difference comes in when the computer has to store a reference data type. When you create a variable and assign it a value that is a reference data type, the computer does not directly store that data type in that variable (as is the case with primitive types).

What you have assigned to that variable is a pointer that points to the location of that data type in memory.

we have two data structures. Astack, and aheap. Say we declared an object, for example. The object itself is stored on a heap, and its pointer is stored on a stack. The pointer is identified by the object's variable name, and points to that object.

    let object1 = {
    name:'Bingeh',
    age:18
    };
    let object2 = object1;
    
    //updating object1,
    object1.age = 20;
    
    console.log(object2); //we see that object2 also updates the age attribute

Another difference comes in when we update object1. If we log both variables to the console, we see that the change affected them both. This is because they are pointing to the same object on the heap – and updating one variable of course affects the other.

You are not logged in.