Understanding Primitives and References in JavaScript
Homayoun Mohammadi
Frontend Developer| JavaScript | React | Next.js | TypeScript Expert | Tailwind CSS | Vitest & React Query Specialist | Building Dynamic Web Apps
In JavaScript, values can be categorized into two types: primitives and references.
Primitive Types:
Primitives include:
- String
- Number
- Boolean
- Null
- Undefined
- Symbol
Primitives store values directly in memory.?
Reference Types:
References include:
- Objects
- Arrays
- Functions
References, as the name suggests, store the memory address (or reference) of the object rather than the actual object.
Example 1: Working with Primitives
Let's take a look at an example with primitive types:
let x = 10;
let y = x;
x = 20;
What do you think the value of y is? It remains 10. This is because x and y are both primitives, and primitives store their values independently. When y is assigned to x, a copy of the value is made. So even when x is changed later, y holds the initial value.
Example 2: Working with Reference Types
Now let’s look at an example with reference types:
let x = { value: 10 };
let y = x;
x.value = 20;
In this case, if we log y.value, it will be 20. This happens because objects are reference types. Both x and y don’t store the object itself; they store the reference to the object. When you update x.value, you’re modifying the object that both x and y reference, so y reflects the same change.