← All animations

📦 Pointers & References

A variable is a labeled box that holds something. Sometimes the box holds the value itself; sometimes it holds an arrow — a reference — pointing at an object that lives elsewhere. Almost every bug about "I changed one and the other changed too" comes from not knowing which kind of box you have. Scroll through to watch the arrows move, mutate things through aliases, and see why a = b; a.x = 1 can surprise you.

1. Boxes & arrows — copy a value vs copy a reference

On the left, a and b are value boxes (think numbers). On the right they are reference boxes whose arrows point at a shared object on the heap. Run b = a, then mutate through one name, and watch what the other name sees. With values the box gets its own copy; with references the arrow is copied, so both names point at the same object.

Press “b = a” to copy

2. The pitfalls — null, dangling, aliasing & pass-by-handle

A reference can point at nothing (null / None / nil) — follow it and you crash. It can also dangle: the object it named was freed, so the arrow points at garbage. And when you pass an object to a function you pass a copy of the arrow, not a copy of the object — so the function can reach back and mutate the caller's data.

A healthy reference points at a live object.

Why a = b; a.x = 1 surprises you: a = b copied the arrow, so a and b are aliases for one object. a.x = 1 mutates that one object — and b.x is now 1 too.

3. Under the hood — stack handles, heap objects & why languages differ

Names live in fast, short-lived stack frames; big objects live on the heap. A reference is just a handle (an address) on the stack pointing into the heap.