mutlu.dev

I recently learned a difference between Primitive types and Reference types. I thought it would be great to write a blog post about this topic.

Let's start with a code snippet

let a = 1;
let b = a;

console.log(b); // 1

a = 2;

console.log(b); // 1

Well this looks okay let's do the same thing with an object

let a = {
  someText: "Hello",
};

let b = a;

console.log(b); // { someText: "Hello" }

a.someText = "Hi";

console.log(b); // { someText: "Hi" }

This performed unexpected isn't it? You will understand why this happens by the end of this post, let's dive into it.

What are primitive and reference types

In Javascript, we have 6 primitive types

  1. String
  2. Number
  3. Boolean
  4. null
  5. undefined
  6. Symbols (ES6)

and 3 Reference types

  1. Object
  2. Array
  3. Function

Primitive types

Primitive types stored in a fixed-sized memory, so exact value of "a" stored in memory, I think an example would be more helpful here

We created variable "a", it placed into memory like this

Alt Text

then we copied memory value of variable "a" to variable "b"

Alt Text

That seems okay let's see what happens with Reference types

Reference Types

Reference types are more complex and take up more space compared to Primitive types. They can't be stored in fixed memory so they stored in a random location in memory let's see it's diagram

Alt Text

Notice that the value stored in memory is not the real value itself, its reference to real value. When we copy the variable "a" to "b" we copy the Memory value (Reference to real object). That's why they're called reference values. When we copy the variable "a" we don't copy the real value, we copy reference to real value.

Alt Text

That's why "b" is also changed when we change the property of "a".

Source

Thanks for reading