Course contentsShow
← JavaScript
Lesson 47 of 2,7232. Values and TypesFree lesson

Assignment Copies References

See how assigning one object variable to another creates two references to the same object in memory.

Assignment Copies References

What you'll learn: When you assign one object variable to another, both variables point to the same object in memory—not separate copies.

The Core Idea

When you assign an object to a new variable, JavaScript doesn't duplicate the object. Instead, it copies the reference (the memory address). Both variables now refer to the exact same object, so changes through either variable affect what both see.

let person1 = { name: "Alice" };
let person2 = person1;  // Copies the reference, not the object

person2.name = "Bob";

console.log(person1.name);  // "Bob" — surprise!
console.log(person2.name);  // "Bob"

Both person1 and person2 point to the same object in memory. Changing name through person2 modifies the shared object, so person1 sees the change too.

Why This Matters

This behavior catches many beginners off guard. If you expect person2 to be an independent copy, you'll be confused when modifying it also modifies person1.

Think of it like two people holding directions to the same house. If someone repaints the house, both people will see the new color when they visit—because there's only one house.

Contrast with Primitives

Remember: primitives copy by value. When you assign a primitive, you get a true duplicate:

let x = 5;
let y = x;  // Copies the value
y = 10;
console.log(x);  // Still 5

With objects, assignment copies the reference, not the value.

Key Takeaway: Assigning one object variable to another creates two references to the same object—changes through either variable affect both.