Value vs Reference Types
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:
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
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:
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.
Okay, let’s continue with a… Plot twist…
Now, Maggie got rid of Alexis’s map and got a new map pointing to another object (house).
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.
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!