[JS] What are reference types?
Key Learnings of This Post
- Understand what reference types are in javascript and their characteristics.
What are reference types?
In JavaScript, reference types (also called non-primitive types) are values that are stored in memory by reference, rather than directly containing their value. When you assign or compare a reference type, you are dealing with a reference to the memory location, not the actual value.
✅ JavaScript Reference Types
| Type | Example | Description |
Objects ({}) | { name: "Alice" } | A collection of key-value pairs |
Arrays ([]) | [1, 2, 3] | A special type of object used for ordered data |
Functions (function) | function add(a, b) { return a + b; } | A callable object that can be assigned to variables |
Dates (Date) | new Date() | Represents a specific point in time |
Regular Expressions (RegExp) | /abc/i | Pattern matching for strings |
Maps (Map) | new Map() | A key-value store that allows any type of key |
Sets (Set) | new Set() | A collection of unique values |
Example
const arr1 = [1, 2, 3];
const arr2 = [1, 2, 3];
console.log(arr1 === arr2); // false (Different references)
// you can assign reference
arr3 = arr1;
console.log(arr1 === arr3); // true (Same memory reference)✅ JavaScript Reference Types v.s. Value Types
| Type | Primitive? | Stored by Value? | Compared by Value? |
Number, String, Boolean, null, undefined, Symbol, BigInt | ✅ Yes | ✅ Yes | ✅ Yes |
Object, Array, Function, Date, RegExp, Map, Set, etc. | ❌ No | ❌ No (Stored by reference) | ❌ No (Compared by reference) |
Summary - characteristics of reference types
✅ Stored in memory by reference
✅ Can be modified even after assignment
✅ Compared by reference, not by value
Comments ()