loading...

JavaScript Primitive vs Reference Types

monicafidalgo profile image 🦊 Atomic Fox Updated on ・2 min read

I started taking the course Accelerated JavaScript Training by Maximilian in Udemy and I found very interesting the why he explained the difference between those types in JavaScript, so I decided to write about that.

In JavaScript, values can have different types and those types can be categorize into 2 categories: Primitive and Reference.

Primitives

Primitive values are simple types like Boolean, String and Number.

When you assign a variable to another variable, then the new value will actually be a copy of the first one. This means that if you change the first variable value, the second variable value(the copy one) will not be changed.

You can do this example in your browser console.

JavaScript Primitives

Reference Types

Reference Types are more complex ones like Object, Arrays and Functions.

When it comes to Reference Types, what we have is not a copy of the value. In this case the value doesn't actually store the data but it only stores a pointer to a place in memory, where data is stored.

Therefore, if you copy a reference type, you copy the pointer. If you change the value of the first value, the value of the second one will also be changed since you changed the data in the memory. The pointer is still the same.

Reference Types JavaScript

So if we try to check if arrayA is equal to arrayB, it will be true, but in a case that we create a new array arrayC with exactly the same values as arrayA and we check for equality, we will get false.

JavaScript Reference Types

Because in arrayC case, we also create a value, an array and we store this in memory too. It's not the same storage place as arrayA, since a new array was created. We know that is exactly the same, but JavaScript doesn't. And that is a good thing because we can add a new value to this array and all of a sudden it wouldn´t be the same anymore.

When we are comparing the objects, we are actually comparing the pointers, and the pointers, point to different locations in memory.

Javascript Reference Types Diagram

I hope you found these tips helpful.😊

Posted on Apr 5 by:

monicafidalgo profile

🦊 Atomic Fox

@monicafidalgo

I’m Mónica, a Front end developer graduated in marine biology. We are always on time to reinvent ourselves.

Discussion

markdown guide