Primitive vs Reference

In javascript there are two types of data types reference and primitive types.

Primitive

As the name suggests these types are of a very basic kind. It includes the following types

  • String
  • Number
  • Boolean
  • Undefined
  • Null
let name = 'Amar'
let age = 22;
let developer = true;

All these are examples of primitive types

Reference

These are not simple and are made up of different types, primitive or reference or both. It includes

  • Array
  • Object

They can also be nested with multiple layers

let student = {
    name:'Amar',
    age:22,
    rollNo:21,
}

let    skills = ['Volleyball', 'React']

Now, these were just the definition differences, what is the real difference?

It is related to how these types are stored in memory in a program. While the primitive types are stored in a stack, the reference types use a combination of stack and heap data structures for storage.

The primitives are stored in a stack directly and can be accessed directly. It's stored like this.

primitive.png

If we assign the value age to newAge variable, a new variable will be created and a new entry into the stack will be made

let name = 'Amar'
let age = 22;
let developer = true;

let newAge = age;

newAge.png

Any changes made to newAge won't reflect in age and vice-versa.

In the case of reference types, unlike primitive types, the value is not directly stored in a stack, but the values are stored in heap and a pointer pointing to the address in heap is stored in the stack, something like this

reference1.png

Now if we make a new object named newStudent and copy the student object into it,

let student = {
    name:'Amar',
    age:22,
    rollNo:21,
}

let newStudent = student;

The newStudent will have a separate entry in the stack but it will hold the address to the same old student object.

reference2.png

What this implies is that now any changes made to one of them will reflect in the other too since both are referring to the same object, in the end, only the path is different.

But sometimes we may want a separate copy of an array object to edit it and not reflect the changes in the original array or object, in such cases, we can use the spread operator.

let student = {
    name:'Amar'
    age:22,
    rollNo:21
}

let newStudent = {...student}

newStudent.name = 'Abhi'

console.log(student.name)
//'Amar'

console.log(newStudent.name)
//'Abhi'

By using the spread operator we are creating a new object and copying the values of the old object and not the address. It can also be used with an array.

Thank you for reading, do comment with your thoughts.

You can try finding out what happens when we have a nested object or array? Can they be copied using spread operator or not? If not then what is the method or trick there?