DEV Community

Ezile Mdodana
Ezile Mdodana

Posted on

Reference vs Value - Javascript

Throughout my programming journey I have struggled to understand the difference between value and reference, and because of that, I have came across quite a huge number of bugs regarding this.

I have also found out that many people do not understand this, especially beginners. Okay,Enough of the BS, let's get into it!.

In Javscript we have the following primitive types

*boolean
*bigint
*null
*number
*string
*symbol
*undefined

All these are easily compared by their value, let's take a look at an example, let's take a look at the snippet below:

Image description

What is the value of b here?
2, you guessed right, as I said before, primitive types are compared directly by their values.
Now, let's take a look at non-primitive types, objects, arrays,...

Let's take a look at the following snippet again,

Image description

As you can see on the console we are printing a, but the content in a has changed, why?🤔
This is because the non-primitive types don't store their values directly in memory, like the primitive types, the non-primitive types actually reference a certain address in memory.

In this example, [10, 20] is stored at some memory address, let's say 00x001, so when we say b = a, we are telling b to reference the same memory address as a, when we b.push(30), b changes the value at the memory address that the two variables, a and b, are referencing, hence the value of a also changes.

Now, take a look at this,

Image description

Here, a and b _have the same values, but when we print _a === b, we get false, why is that? Because now, we initialized a, and we initialize b, so a and b have different memory address, hence
a === b gives us false.

In conclusion, primitive types are compared by value, but non-primitive types are compared by reference, in memory.

Thank you for reading.
Happy Coding!🤓🤓

Top comments (0)