Primitive and Reference Datatypes in Javascript With Examples

Primitive and Reference Datatypes in Javascript With Examples

In javascript, the datatypes are divided into two types

  1. Primitive Type(Primitive Datatypes)

  2. Non-Primitive Type(Reference Type)

Primitive Type:

when we declare a variable or a function after the declaration, it needs to be stored somewhere but where it is stored.? so all our primitive datatypes will be stored inside the stack, Javascript will store all our primitive datatypes inside the stack , The primitive datatypes are

  • Number

  • String

  • Boolean

  • undefined

  • null

  • BigInt

  • Symbol

now let's get into an example :

let first_username = "deepak"
let second_username = first_username

so here in this example, the first_username and the second_username will be having different memory, if I will do any changes to any one of them, I mean if I will change the name in any of the variables then the changes will not affect+ the other one

let first_username = "deepak"
let second_username = first_username

first_username = "rahul krishna vaidya"
console.log(second_username)
console.log(first_username)

/* Output */
deepak
rahul krishna vaidya

so I have changed the value of first_username, but still, after changing also it will not reflect those changes to the other variable, because both are having different memory.

Note:

  1. Primitive Datatypes/ Primitive values take less memory space

  2. let second_username = first_username. in this line, the javascript behind the scenes is creating a copy of first_username and assigning it to second_username

Reference Datatypes(Reference Type)

The Javascript stores the reference type/reference datatypes inside the Heap. The primitive values are stored inside the Stack and the reference are stored inside the Heap

Array, Objects are known as non-primitive values let's get into an example:

let username = "deepak kumar"
let city = "Kolkotta"

personDetails = {
    username :"deepak",
    city: "Kolkotta"
}

let username = "deepak kumar"
let city = "Kolkotta"

personDetails = {
    username :"deepak",
    city: "Kolkotta"
}

let personData = personDetails

from the above diagram, its is pretty clear that persondetails and personData both are pointing out to the same object/address

Though it is pointing out to the same address that's why if we do any changes to persondetails then the other one(personData) will also get affected.

reference values allow us to change its values, properties

let username = "deepak kumar"
let city = "Kolkotta"

personDetails = {
    username :"deepak",
    city: "Kolkotta"
}

let personData = personDetails

personData.name = "rahul krishna vaidya"

console.log(`value of username from personDetails: ${personDetails.name}`)
console.log(`value of username from personData: ${personData.name}`)

/* Output */
value of username from personDetails: rahul krishna vaidya
value of username from personData: rahul krishna vaidya