In this article, we’re going to cover the concepts of variable assignment and mutation and see why — together — they can be a real pain for developers. We’ll look at how to manage them to avoid problems, how to use as few as possible, and how to keep your code predictable.
Let’s start by going back to the very basics of value types …
- numbers, such as
- strings, such as
- symbols — a unique token that’s guaranteed never to clash with another symbol
BigInt— for dealing with large integer values
Anything that isn’t a primitive value is an object, including arrays, dates, regular expressions and, of course, object literals. Functions are a special type of object. They are definitely objects, since they have properties and methods, but they’re also able to be called.
Variable assignment is one of the first things you learn in coding. For example, this is how we would assign the number
3 to the variable
const bears = 3;
A common metaphor for variables is one of boxes with labels that have values placed inside them. The example above would be portrayed as a box containing the label “bears” with the value of 3 placed inside.
An alternative way of thinking about what happens is as a reference, that maps the label
bears to the value of
If I assign the number
3 to another variable, it’s referencing the same value as bears:
let musketeers = 3;
musketeers both reference the same primitive value of 3. We can verify this using the strict equality operator,
bears === musketeers << true
The equality operator returns
true if both variables are referencing the same value.
Some gotchas when working with objects
The previous examples showed primitive values being assigned to variables. The same process is used when assigning objects:
const ghostbusters = number: 4 ;
This assignment means that the variable
ghostbusters references an object:
A big difference when assigning objects to variables, however, is that if you assign another object literal to another variable, it will reference a completely different object — even if both object literals look exactly the same! For example, the assignment below looks like the variable
tmnt (Teenage Mutant Ninja Turtles) references the same object as the variable
let tmnt = number: 4 ;
Even though the variables
tmnt look like they reference the same object, they actually both reference a completely different object, as we can see if we check with the strict equality operator:
ghostbusters === tmnt << false