Value vs Reference Types

VALUE VS REFERENCE.png

When I started learning JavaScript, one of the topics that confused me at the beginning was understanding the difference between value and reference. In this post, I’ll guide you through examples with pictures how copy by value and reference work in JavaScript. Let’s get started...

Let’s begin with looking at the graph below with the different data types that exist in JavaScript:

IMG_0154.JPG

Now that we look at the different data types, we’ll talk in more detail about the two ways you can assign/pass them.  

PASSED BY VALUE

primitive 1.png

What does passed by value really mean? When a variable with a primitive value is assigned to another variable using an equal sign (=), the value is copied to the new variable. 

primitive 2.png

Something important to keep in mind is that even if we change one of the variables to a new value, it won’t affect the other. The variables do not have a relationship between them, they were just copied.

PASSED BY REFERENCE

For this somehow confusing part, we’ll use a story example and we’ll connect that with the code and you’ll see everything will make more sense this way. Let’s dive in…

Composite data types are also known as Objects. When an object data type  is assigned to a variable, they are given a reference to that value. They do not contain the actual value. 

When you create an object, you get an ‘address’ to the location in your computer’s memory where the object you created is stored. To better understand this, lets look at the following example:

reference 1.png

Alexis is assigned a house and he is provided a map to find it. We’ll call it ‘Alexis’s map’. Logically, we know that ‘Alexis’s map’  is not the actual house, but an “address” to get to it, right? 

2.JPG
reference 2.png

Alexis is excited and wants to share the house that was assigned to him with Maggie. He gives her a copy of his map (‘Alexis’s map’). So now, Maggie can access the house as well.

Looking at the code above, we know that Maggie has a copy of Alexis’s map and since she has the same access as Alexis to the house, she changes the attribute houseColor to green. Since Alexis and Maggie’s map point to the same object (house), if we access houseColor through the Alexis variable, we’ll see that houseColor changed to green.

IMG_0151.JPG

Okay, let’s continue with a… Plot twist…

reference 3.png

Maggie is assigned a new house.

Now, Maggie got rid of Alexis’s map and got a new map pointing to another object (house). 

3.JPG

At the end, Alexis and Maggie can change their houses attributes as they like and they won’t change each other’s houses, thanks to both having different maps to different objects.

final.png

I hope this was useful and entertaining for you. Remember to write some code and practice until you feel comfortable with the concepts. Happy coding! 

Previous
Previous

Fetch API