References: Two Names, One Object

Why copying a variable that holds an object copies only the note that says where it is, so two names can change one object; how to make a real copy; and null, None and undefined, the note that points at nothing.

Apprentice · C# · Java · Python · JavaScript · TypeScript · Updated

By

After this lesson you can

  • Predict what happens when two variables refer to the same object and one of them changes it
  • Explain null, None and undefined as a reference that points at nothing

Key takeaways

  • A variable that holds an object really holds a reference, a note saying where the object is in memory.
  • Copying that variable copies the note, not the object, so both names reach the same object and see each other's changes.
  • A real copy is a new object made from the old one's values. It changes on its own.
  • null (C#, Java), None (Python) and null or undefined (JavaScript, TypeScript) mean a reference that points at nothing. Check for it before you use it.

The snack stand's owner writes "Pretzel inventory: second shelf, left side" on a sticky note and hands a copy of the note to a new helper. Now two people have a note, but there's still only one shelf of pretzels. When the helper sells the last pretzel, the owner's note leads to an empty shelf too. Variables that hold objects work exactly like those notes, and linked lists, trees and graphs (the structures of Modules 2, 6 and 7) are built from them.

Two names, one object

In Why "Play Track 750,000" Is Instant and "Find Golden Hour" Isn't: Memory as Mailboxes you met the reference: a note that says which box to look in. When a variable holds an object, such as a Snack, it really holds a reference to it. Copying the variable copies the note, not the object. Both names now lead to the same object, so a change made through one is seen through the other.

A real copy is different: a new object, made from the old one's values. It has its own fields and changes on its own.

The pretzels, one object and a copy

Snack owners = new Snack("Pretzel", 12);
Snack helpers = owners;
helpers.Count = 0;
Console.WriteLine("The owner's note shows: " + owners.Count + " left");

Snack copy = new Snack(owners.Name, 12);
copy.Count -= 5;
Console.WriteLine("The copy shows: " + copy.Count + " left; the owner's note still shows: " + owners.Count);

Snack? special = null;
Console.WriteLine("Today's special set? " + (special != null ? "yes" : "no"));

class Snack
{
    public string Name;
    public int Count;

    public Snack(string name, int count)
    {
        Name = name;
        Count = count;
    }
}
The owner's note shows: 0 left
The copy shows: 7 left; the owner's note still shows: 0
Today's special set? no
class Snack {
    String name;
    int count;

    Snack(String name, int count) {
        this.name = name;
        this.count = count;
    }
}

void main() {
    Snack owners = new Snack("Pretzel", 12);
    Snack helpers = owners;
    helpers.count = 0;
    IO.println("The owner's note shows: " + owners.count + " left");

    Snack copy = new Snack(owners.name, 12);
    copy.count -= 5;
    IO.println("The copy shows: " + copy.count + " left; the owner's note still shows: " + owners.count);

    Snack special = null;
    IO.println("Today's special set? " + (special != null ? "yes" : "no"));
}
The owner's note shows: 0 left
The copy shows: 7 left; the owner's note still shows: 0
Today's special set? no
class Snack:
    def __init__(self, name, count):
        self.name = name
        self.count = count


owners = Snack("Pretzel", 12)
helpers = owners
helpers.count = 0
print(f"The owner's note shows: {owners.count} left")

copy = Snack(owners.name, 12)
copy.count -= 5
print(f"The copy shows: {copy.count} left; the owner's note still shows: {owners.count}")

special = None
print(f"Today's special set? {'yes' if special is not None else 'no'}")
The owner's note shows: 0 left
The copy shows: 7 left; the owner's note still shows: 0
Today's special set? no
class Snack {
  constructor(name, count) {
    this.name = name;
    this.count = count;
  }
}

const owners = new Snack("Pretzel", 12);
const helpers = owners;
helpers.count = 0;
console.log(`The owner's note shows: ${owners.count} left`);

const copy = new Snack(owners.name, 12);
copy.count -= 5;
console.log(`The copy shows: ${copy.count} left; the owner's note still shows: ${owners.count}`);

const special = null;
console.log(`Today's special set? ${special !== null ? "yes" : "no"}`);
The owner's note shows: 0 left
The copy shows: 7 left; the owner's note still shows: 0
Today's special set? no
class Snack {
  name: string;
  count: number;

  constructor(name: string, count: number) {
    this.name = name;
    this.count = count;
  }
}

const owners = new Snack("Pretzel", 12);
const helpers = owners;
helpers.count = 0;
console.log(`The owner's note shows: ${owners.count} left`);

const copy = new Snack(owners.name, 12);
copy.count -= 5;
console.log(`The copy shows: ${copy.count} left; the owner's note still shows: ${owners.count}`);

const special: Snack | null = null;
console.log(`Today's special set? ${special !== null ? "yes" : "no"}`);
The owner's note shows: 0 left
The copy shows: 7 left; the owner's note still shows: 0
Today's special set? no

Read the first line of output carefully. The code set helpers.Count to 0, never owners.Count, yet the owner's note shows 0. There was only ever one pretzel object, with two notes pointing at it. The copy, made with new, is a second object: selling 5 from it touched nothing else.

Two sticky notes, labeled owners and helpers, each with an arrow to the same single Pretzel object showing 0 left; beside them, a separate Pretzel object labeled copy, showing 7 left, with its own arrow from a note labeled copy

Lists work the same way: List<string> b = a; gives two names for one list, and adding through b adds to a. JavaScript's const doesn't change this: it means the name always holds the same note, not that the object behind it can't change.

A note that points at nothing

Sometimes a variable has no object yet: the stand hasn't picked today's special. Its note says, in effect, "nowhere". Each language has a word for that:

Language A reference to nothing
C# and Java null
Python None
JavaScript and TypeScript null, and also undefined for a variable or property that was never given a value

Following a reference to nothing is one of the most common errors in programming: ask for special.Count when special is null, and the program stops (C# says NullReferenceException, Java NullPointerException, Python 'NoneType' object has no attribute, JavaScript Cannot read properties of null). So check before you use it, as the last line of the code does. You'll do this check constantly in linked lists and trees, where the last item's "next" note points at nothing.

C# marks a variable that may hold null with a question mark, Snack?, and TypeScript writes Snack | null, so the language can remind you to check.

Try it. After the line that sets helpers.Count to 0, add one that sets owners to a brand-new Snack("Pretzel", 20). Now print helpers.Count. Does it show 0 or 20, and why?

Check yourself

2 questions to try on the lesson page.

So what

"Two names, one object" is behind some of the most confusing bugs beginners meet, and behind every structure built from links: a linked list's next item, a tree's children, a graph's neighbors. Every one of them is a reference, and every one can point at nothing.

Key terms

Cheat sheets