66. Objects as Reference Types
This is one of the most critical concepts for understanding how JavaScript manages data.
Primitives vs. References
- Primitives (
string,number,boolean,null,undefined) are stored by value. When you copy a primitive, you get a completely new, independent value. - Objects (
{}), Arrays ([]), and Functions are stored by reference. The variable holds a pointer (address) in memory to where the data lives. When you copy an object variable, you are copying the pointer, not the data itself.
The Reference Problem
If two variables hold the same object reference, changing the object through one variable changes it for the other.
javascript let user1 = { name: 'Alex', score: 10 }; let user2 = user1; // user2 points to the SAME object in memory as user1
console.log(user1.score); // 10
// Change made via user2 user2.score = 50;
console.log(user1.score); // Output: 50 (user1 was also changed!)
// To truly copy an object, we need to use cloning techniques (like spread syntax, covered later).
Reference Equality
Two objects are only strictly equal (===) if they reference the exact same spot in memory.
javascript console.log({ a: 1 } === { a: 1 }); // false (They are two different objects) console.log(user1 === user2); // true (They share the same memory reference)