Handling data - value vs reference
Understanding how data is handled is a valuable skill that will help you to create optimal, bug free solutions.
Let’s dive into the difference between how primitive and non-primitive data is handled with a couple of examples.
Primitives are accessed directly by value, which means when referencing a variable assigned to a primitive you are directly referencing that data.
Primitives are immutable, their value cannot be altered once set.
This may seem confusing as you can update a variable that references a primitive value. However, what actually happens is the value that the variable references changes, the value itself is not changed.
Primitives are compared by value, for example:
It doesn’t matter that the variables are not the same, all that matters is that the values assigned to them are.
Non-primitive values (Object references)
Non-primitive data types are types of objects, which includes:
As non-primitives are more complex data structures and can have properties and methods these are stored on the heap.
One of the notable differences between primitive and non-primitive data is what happens when we try to reference existing data. This is because non-primitive data is handled by reference.
In this example we have two sliders with options passed by object. We want both to have the same settings but with one altered property. Rather than creating the same object twice we’ve decided to simply copy the first object and change one of the values, sounds straightforward enough!
If you run this code in your console you should see an output of:
You may be surprised to see both objects are exactly the same, so what’s actually happened?
We’ve then created a variable called ‘sliderTwoOptions’ and pointed that to ‘sliderOneOptions’. As this is just a reference to the location of the ‘sliderOneOptions’ object in memory this just adds a marker to ‘sliderTwoOptions’, which points to the same location in memory.
As both variables are referencing the same object in memory. This means when we change a value on the object by referencing either variable it actually changes the same object.
Non-primitives are mutable and can be altered after being assigned.
Non-primitives are compared by reference, you can see this in the following example:
When comparing two objects that contain the exact same properties we see these don’t match, this is because we’re checking if it references the same object in memory, which it doesn’t. We can see further evidence of this when comparing the ‘sliderOneOptions’ and ‘sliderThreeOptions’ that both reference the same object.