← Fundamentals
Fundamentals

References, pointers, and handles

What does a value that refers to something else contain?

Distinguish access to an object from its contents, position, and external identity.

Outcome

Say what a reference, pointer or handle holds; tell assigning to it from assigning through it; say what comparing references compares in each language; and spot a handle that was reused or a reference whose target moved.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Reference
A value that leads to another value kept elsewhere, used instead of a copy of it.
Pointer
A reference that holds an address and can be read, compared or changed as a value.
Indirection
Reaching a value through something that refers to it.
Handle
A number or key that stands for a thing kept in a table and is looked up to reach it.
Dangling
Describes a pointer or reference whose target is no longer valid to access because its lifetime ended or its storage was invalidated. A live target left outside the current collection is a separate membership issue.

Values that lead to other values

A reference or pointer provides access to a value stored elsewhere. Follow the distinction between changing an access path and changing the value reached through it. The native type determines whether that path can be redirected, which comparisons it supports and how its lifetime is controlled.

A handle adds a lookup step: an ID is resolved through a table to reach its target. An ID, a collection position and a storage address express different relationships. Keeping one around requires knowing what growth, removal or replacement means for that particular relationship.

01To or through

Re-pointing a reference is different from changing what it names

A bulk-stock editor keeps mutable stock records with a product name and kilograms on hand. Delivery imports update these records; lookups compare the requested stock value. Growth and deletion can change storage or list positions. External record IDs must keep selecting the same record when another record is inserted or removed.

The delivery editor keeps one current selection, called scoop. This reduced probe selects green, writes its quantity, then selects black and writes again. Predict the two stored weights.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Tub = { name: string; kg: number };

const green: Tub = { name: "green", kg: 5 };
const black: Tub = { name: "black", kg: 2 };

let scoop = green;
scoop.kg = 3;
scoop = black;
scoop.kg = 1;

console.log(green.name, green.kg, black.name, black.kg);
What is printed?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts

Use the setup from the first reading for your language. Check the selected native command and consider both acceptance and output when making a prediction.

02Comparing references

Comparing references compares places in some languages and values in others

An imported lookup request is a new value, even when its name and kilograms match a stored record. Before building the search, compare that request with the second stored tub: do the two comparisons ask the same question?

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Tub = { name: string; kg: number };

const tubs: Tub[] = [
  { name: "green", kg: 5 },
  { name: "black", kg: 2 }
];
const wanted: Tub = { name: "black", kg: 2 };

console.log(
  tubs[1] === wanted,
  tubs[1]!.name === wanted.name && tubs[1]!.kg === wanted.kg
);
What is printed?

03Handles

A handle is a number that stands for something kept elsewhere

The editor also keeps a record ID while its detail panel is open. This candidate allocator numbers tags with count plus one. Hold tag 2, remove tag 1, then add another tub: what does the held ID resolve to?

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const tubs = new Map<number, string>();

const add = (name: string) => {
  const tag = tubs.size + 1;
  tubs.set(tag, name);

  return tag;
};

add("green");
const held = add("black");
tubs.delete(1);
add("kalamata");

console.log(held, tubs.get(held));
What is printed?
Loading The same number can look up a different tub…

04When the target moves

A reference can outlive, lose or no longer match what it named

Unique IDs settle allocation, but the lookup table still needs a reliable route to each record. Keep a direct selection while the list grows or drops an entry, then check what that selection still reaches.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Tub = { name: string; kg: number };

const tubs: Tub[] = [{ name: "green", kg: 5 }];
const held = tubs[0]!;

tubs.push({ name: "black", kg: 2 });
tubs.splice(0, 1);
held.kg = 9;

console.log(held.name, held.kg, tubs.length);
What is printed?

05Repair the stock-record editor

Restock, find by contents, then keep tags right

Repair the stock-record editor: apply deliveries to the retained records, locate an exact requested name-and-quantity value, then maintain durable IDs across removal, sale and insertion.

Tub is the native source’s stock-record type; its name is a product key and kg is its stored quantity. Product labels are sample data. IDs belong to records and are independent of compacted storage positions. A recorded sale may take a balance below zero; the editor keeps that deficit for reconciliation.

Repair the stock-record editor

Apply deliveries to stored quantities, locate the first exact stock value, and preserve record IDs through sales and deletion.

  1. easy · F-REF-V4-1 Restock a tub
  2. medium · F-REF-V4-2 Find a tub by its contents
  3. hard · F-REF-V4-3 Keep tags on their tubs
In the frontend Resolve the selected record ID against the current rows. Optional

A stock detail panel can keep selectedId while rows are replaced or compacted. Resolve that ID from the current rows before displaying its quantity. A removed ID should show a removed-record state; the row that shifted into its old position is a different selection.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Row = { id: number; name: string; kg: number };

export default function StockDetail({
  rows,
  selectedId
}: {
  rows: Row[];
  selectedId: number;
}) {
  const selected = rows.find((row) => row.id === selectedId);

  return <p>{selected ? selected.name + ": " + selected.kg : "Record removed"}</p>;
}

Each render reads the supplied current rows and computes a selection without mutating props. The parent must retain unique record IDs and publish changed rows; this display does not allocate IDs or repair a stale table.

Sources: React: keeping components pure,Svelte: $derived.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.