Reference Types
Overview
Unlike Primitives, Reference Types are complex objects that can hold collections of data.
In JavaScript, Objects, Arrays, and Functions are all Reference Types. When you create them, you aren't storing the data directly in the variable; you are storing a pointer (reference) to where the data lives in memory.
Syntax
Both person1 and person2 point to the exact same house in memory. If person2 paints the house blue, person1 also sees a blue house.
const person1 = { name: "Kartik" };
const person2 = person1; // Copies the REFERENCE, not the actual object!
person2.name = "Aman";
console.log(person1.name); // "Aman" (Wait, I didn't touch person1!)Common Pitfalls
- Accidentally mutating original arrays or objects when you meant to create a copy. Always use the Spread Operator (
...) to create independent shallow copies.
Interview Questions
Because Arrays are Reference Types. The equality operator compares memory addresses, not the contents. Since the two arrays were created separately, they point to different locations in memory.
Real-World Example
In Redux or React State, you are forbidden from mutating Reference Types directly because React uses memory references to detect changes. If the reference doesn't change, the UI won't update!
// BAD in React: Mutating the reference
state.items.push(newItem);
// GOOD in React: Creating a brand new reference
setItems([...state.items, newItem]);Check Your Knowledge
Test your understanding of Reference Types with these quick questions.