Skip to content

Mutludev's Blog

Weird behaviors of javascript: Primitive Types and Reference Types

1 min read

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

1let a = 1;
2let b = a;
3
4console.log(b); // 1
5
6a = 2;
7
8console.log(b); // 1

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

1let a = {
2 someText: 'Hello',
3};
4
5let b = a;
6
7console.log(b); // { someText: "Hello" }
8
9a.someText = 'Hi';
10
11console.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

diagram 1

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

diagram 2

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

diagram 3

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.

diagram 4

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

Source

  • https://github.com/leonardomso/33-js-concepts
    • Section 3. Value Types and Reference Types

Thanks for reading

© 2020 by Mutludev's Blog. All rights reserved.
Theme by LekoArts