Reference types in Javascript
Introduction
In JavaScript, the distinction between primitive and reference data types is confusing for programmers.
In this guide we will explain the difference and focus mostly on how reference works in Javascript.
We have an article with all data types in javascript here: Data Types in Javascript
Difference Between Primitive and Reference Data Types
Primitive data types
Primitive data types include Number
, String
, Boolean
, null
, undefined
, Symbol
, and BigInt
.
They are immutable and stored directly in the variable.
Reference data types
Reference data types include Object
, Array
, and Function
.
They store a reference (memory address) to the actual value, not the value itself.
Key differences
Primitives
are copied by value.Reference types
are copied by reference, meaning variables share the same memory location.
What it memory reference?
When assigning a reference data type to another variable, both variables point to the same memory location.
In computer science terms, when you create an object
or an array
, Javascript allocates a space in memory for that entity.
For instance, consider an object stored in memory at address 0x0001
.
In the above example, obj1
is created and stored at memory address 0x0001
.
When obj2
is assigned to obj1
, it does not create a new object.
Instead, obj2
holds the reference to the same memory address 0x0001
.
So, any changes made through obj2
reflect in obj1
because both variables point to the same location in memory.
Let's look at it visually:
After changing obj2.name
to Bob
:
Tricky examples 🍬
Object Assignment
To avoid referencing the same memory location, use Object.assign
or even better the spread operator (...)
.
Example with spread operator:
Arrays
Arrays
are reference types
too, so they have similar behavior.
To avoid referencing the same memory location, use the spread operator (...)
or Array.from
.
Best practices
- Avoid unintended mutations: Always be cautious when assigning reference types to multiple variables.
- Use deep cloning: For nested objects, use libraries like
Lodash
or structured cloning algorithms for deep cloning.
Example with loadash
:
Summary
Understanding how reference works in Javascript is quite important yet a lot of
new developers procrastinate on it. Not knowing how objects
work can lead to huge
bugs in your production code while trying to copy or reassign values.
Please understand and study this topic deeply, it's not that hard.