Functions Receive References to Objects
What you'll learn: How passing an object to a function actually passes a reference, allowing the function to modify the original object.
The Core Idea
When you pass an object to a function, JavaScript doesn't create a copy of that object. Instead, it passes the reference — the memory address pointing to the object. This means the function parameter and your original variable both point to the same object in memory.
Because of this, any changes the function makes to the object's properties will affect the original object outside the function.
How It Works
function changePersonName(person) {
person.name = "Bob";
}
const user = { name: "Alice" };
changePersonName(user);
console.log(user.name); // "Bob" — the original object was modified!
The parameter person received a reference to the same object that user points to. When we modified person.name inside the function, we modified the object itself, so user.name also changed.
An Analogy
Think of an object as a house, and the reference as the house's address. When you pass the address to a friend (the function), they can visit the actual house and rearrange the furniture. They're not working in a copy of the house — they're in the real one. When you go back home, you'll see the changes they made.
Important Distinction
Reassigning the parameter itself doesn't affect the original variable:
function replaceUser(person) {
person = { name: "Charlie" }; // This creates a NEW object
}
const user = { name: "Alice" };
replaceUser(user);
console.log(user.name); // Still "Alice" — user still points to the original object
Key Takeaway: Functions receive references to objects, not copies, so modifying object properties inside a function affects the original object outside.