Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

References & ownership

Borrow access or pass an address

TypeScript

Arguments are passed by value; for an object, the passed value identifies the same object. A function can mutate that object, but rebinding its local parameter does not rebind the caller’s variable. There is no general address-of operator.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
function increment(box: { count: number }): void {
  box.count += 1;
}

const box = { count: 2 };
increment(box);

Recognize owning and shared handles

TypeScript

Objects are garbage collected when no longer reachable according to the runtime’s rules. Keeping an ordinary reference keeps access to the same object; this does not provide deterministic file/socket cleanup.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const first = { name: "north" };
const second = first;

// Both bindings refer to the same object.

Read lifetime-related notation

TypeScript

Closures can retain access to captured variables after the outer call returns. TypeScript does not express Rust-style borrow lifetimes in ordinary function types. A retained reference can keep a large object graph reachable.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
function counter() {
  let value = 0;

  return () => {
    value += 1;
    return value;
  };
}

const next = counter();

Copy or move a value: reference semantics, value copies, move, Copy/Clone, std::move

TypeScript

Beyond spotting shared storage (the copying entry), this shows how to make the copy you need, shallow or deep. Primitives (number, string, boolean, bigint, symbol, null, undefined) are copied on assignment. Objects, arrays, maps and class instances are reached through a reference: assigning or passing one copies the reference, so every name sees the same object. There is no move and no copy constructor. Spread ({ ...o }, [...a]) and Object.assign make shallow copies; structuredClone copies a graph of plain data (including Map, Set, Date and cycles) but not functions, and it drops class prototypes.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

type Stop = { name: string; minutes: number };
type Route = { id: string; stops: Stop[] };

// Primitives (number, string, boolean, bigint...) are copied on assignment.
let fare = 250;
let discounted = fare;
discounted -= 50;
assert.equal(fare, 250);

// Objects and arrays: assignment copies the reference, so both names see one object.
const route: Route = { id: 'R1', stops: [{ name: 'Depot', minutes: 0 }] };
const alias = route;
alias.id = 'R1-renamed';
assert.equal(route.id, 'R1-renamed');

// Spread makes a shallow copy: a new top-level object whose nested values are still shared.
const shallow = { ...route };
shallow.id = 'R2';
shallow.stops.push({ name: 'Harbor', minutes: 12 });
assert.equal(route.id, 'R1-renamed'); // top level is independent
assert.equal(route.stops.length, 2); // the stops array is the same array

// structuredClone copies the whole graph of plain data (not functions or class prototypes).
const deep = structuredClone(route);
deep.stops[0].minutes = 5;
assert.equal(route.stops[0].minutes, 0);

// Arguments follow the same rule: the callee receives a copy of the reference.
function delay(stop: Stop, by: number): void {
  stop.minutes += by; // visible to the caller
}
function delayed(stop: Stop, by: number): Stop {
  return { ...stop, minutes: stop.minutes + by }; // caller's object untouched
}
delay(route.stops[1], 3);
const late = delayed(route.stops[1], 10);
console.log(route.stops[1].minutes, late.minutes); // 15 25
console.log(JSON.stringify(route));

In practice: treat objects you receive as shared. Return a new object instead of mutating an argument, use spread when only the top level changes, and structuredClone when nested data must be independent.

structuredClone throws DataCloneError on functions, DOM nodes and some host objects, and returns plain objects for class instances, so methods are lost.

JSON.parse(JSON.stringify(x)) is not a deep copy: it drops undefined, functions and symbols, turns Dates into strings and fails on cycles and bigint.

readonly and as const are compile-time only; they do not copy or freeze anything at run time.

Choose an owning pointer: GC references, Box/Rc/Arc/Weak, unique_ptr/shared_ptr/weak_ptr

TypeScript

Beyond recognizing handles (the ownership entry), this covers the one choice TypeScript offers: a strong or a weak reference. Memory is garbage collected. Every ordinary reference is a strong, shared one: an object lives while anything reachable refers to it, and cycles are collected. There is nothing like unique ownership or reference counting to choose. The only other kind is weak: WeakMap and WeakSet hold entries keyed by an object without keeping that object alive, and WeakRef holds a reference the collector may clear.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

type Order = { id: string; cents: number };

// Ordinary references are strong: any of them keeps the object alive.
let order: Order | null = { id: 'A-1', cents: 4_200 };
const queue: Order[] = [order];

// WeakMap: metadata about an object that must not keep it alive (no iteration, no size).
const auditNotes = new WeakMap<Order, string[]>();
auditNotes.set(order, ['created']);
auditNotes.get(order)?.push('paid');
assert.deepEqual(auditNotes.get(order), ['created', 'paid']);

// WeakRef: a cache entry the collector may clear; always handle deref() === undefined.
const lastViewed = new WeakRef(order);
const seen = lastViewed.deref();
console.log(seen ? `last viewed ${seen.id}` : 'last viewed was collected');

// Dropping our own reference is not enough: the queue still holds a strong one.
order = null;
console.log(queue[0].id, queue.length); // A-1 1
queue.length = 0; // now nothing strong remains; collection happens later, if ever

In practice: use plain references. Reach for WeakMap to attach metadata to objects you do not own, and WeakRef only for caches of values you can recompute; always handle deref() returning undefined. Leaks in TypeScript come from strong references you forgot: listeners, caches, timers and closures.

Collection timing is unspecified: a WeakRef target may survive long after its last strong reference, or be cleared at the next turn.

FinalizationRegistry callbacks may never run; do not use them to close files or sockets (see the RAII entry).

Mutate shared state safely: aliasing, pointer receivers, &mut, RefCell/Mutex, const

TypeScript

Beyond passing references (the references entry), this lists the aliasing bugs that shared mutable objects cause and the copying methods that avoid them. Any number of references may point at one object and any of them may change it; the language has no notion of an exclusive or read-only handle at run time. Bugs come from aliasing you did not intend: Array.prototype.fill with an object puts the same object in every slot, sort() and reverse() mutate the array in place, and a getter that returns an internal array lets callers edit it. Because JavaScript runs one thread per realm, there are no data races, but state shared across await points can still change between steps.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// Pitfall 1: fill() puts the SAME array in every slot.
const sharedRows = new Array<number[]>(3).fill([]);
sharedRows[0].push(1);
assert.deepEqual(sharedRows, [[1], [1], [1]]);
const rows = Array.from({ length: 3 }, (): number[] => []); // one new array per slot
rows[0].push(1);
assert.deepEqual(rows, [[1], [], []]);

// Pitfall 2: sort() and reverse() mutate in place, including arrays the caller still uses.
const prices = [30, 10, 20];
const sorted = prices.toSorted((a, b) => a - b); // ES2023: returns a new array
assert.deepEqual([prices, sorted], [[30, 10, 20], [10, 20, 30]]);

// Pitfall 3: returning internal state hands callers a handle to mutate it.
class Cart {
  #items: string[] = [];
  add(item: string): void {
    this.#items.push(item);
  }
  // ReadonlyArray stops writes at compile time; a copy stops them at run time as well.
  get items(): readonly string[] {
    return [...this.#items];
  }
}
const cart = new Cart();
cart.add('tea');
const view = cart.items;
// view.push('coffee'); // error TS2339: Property 'push' does not exist on type 'readonly string[]'.
(view as string[]).push('coffee'); // a cast gets past the type, but only changes the copy
assert.deepEqual(cart.items, ['tea']);

// One owner applies changes; others get a fresh value instead of a shared mutable one.
type Settings = { readonly theme: string; readonly fontSize: number };
let settings: Settings = { theme: 'light', fontSize: 14 };
const before = settings;
settings = { ...settings, fontSize: 16 };
console.log(before.fontSize, settings.fontSize, sharedRows.length); // 14 16 3

In practice: give each piece of mutable state one owner that changes it, and hand others copies or readonly views. Prefer the copying methods toSorted, toReversed, toSpliced and with (ES2023, Node 20+), and replace objects ({ ...s, field }) instead of editing them.

readonly string[] stops writes through that type only; the same array may still be changed through another, mutable reference.

Object.freeze is shallow and makes writes throw only in strict mode (always the case in ES modules).

SharedArrayBuffer shared with workers is the one case with real concurrent writes; use Atomics there.

Avoid dangling references: stale handles, loop captures, borrow errors, use-after-free

TypeScript

Beyond reading lifetime notation (the lifetime-notes entry), this covers the staleness bugs that remain under garbage collection. Garbage collection makes use-after-free impossible: anything you can reach stays alive. What remains is the logical version. A reference held to an object or array that the owner has since replaced still works but shows old data. Closures capture bindings, and a var loop variable is one binding for the whole loop, so every callback sees its final value; let and const create a fresh binding per iteration. Long-lived references (listeners, timers, caches) also keep whatever their closures capture alive.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// The collector never frees an object you can still reach, so there is no use-after-free.
// What remains is the logical version: a reference to data that is no longer current.

// 1. var is function-scoped: every closure captures the same binding.
const withVar: Array<() => number> = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
assert.deepEqual(withVar.map((f) => f()), [3, 3, 3]);
// let creates a fresh binding per iteration.
const withLet: Array<() => number> = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);
assert.deepEqual(withLet.map((f) => f()), [0, 1, 2]);

// 2. A stale reference: the store replaced its array, the old handle still sees the old one.
const store = { items: ['tea'] };
const snapshot = store.items;
store.items = [...store.items, 'coffee'];
assert.deepEqual(snapshot, ['tea']); // alive, but out of date

// Fix: keep a way to read the current value, not the value itself.
const currentItems = () => store.items;
assert.deepEqual(currentItems(), ['tea', 'coffee']);

// 3. A listener that is never removed keeps its closure (and everything it captures) alive.
const listeners = new Set<(n: number) => void>();
const big = new Array<number>(1_000).fill(0);
const onTick = (n: number) => {
  big[0] = n;
};
listeners.add(onTick);
listeners.forEach((l) => l(7));
listeners.delete(onTick); // unsubscribe when the owner goes away
console.log(withVar.length, snapshot.length, big[0], listeners.size); // 3 1 7 0

In practice: use let or const in loops, never var. Keep a way to read the current value (a getter, a store lookup, an id) rather than a long-lived snapshot. Unsubscribe listeners and clear timers when their owner goes away.

The same staleness hits UI code: a callback that closed over an old state value (a stale closure) keeps reading it.

An AbortController signal passed to addEventListener removes many listeners at once when aborted.

Release resources by ownership: using and Symbol.dispose, Close conventions, Drop, RAII and deleters

TypeScript

Beyond recognizing cleanup code (the cleanup entry), this shows how to give each resource an owner that releases it, including handing ownership to a caller. Garbage collection frees memory but never closes files, sockets or locks. The standard protocol is a [Symbol.dispose]() method (Symbol.asyncDispose for async). A using declaration calls it when the block exits, in reverse order of declaration, whether the block returns or throws; await using does the same for async disposal. DisposableStack holds several disposables while they are acquired, releases them if a later step fails, and move() transfers them to a new owner on success.

Complete program

Complete program. Needs Node 24+ (using and DisposableStack). Type-checks with TypeScript 5.2+ and lib esnext.disposable, or target esnext.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

const log: string[] = [];

class Connection implements Disposable {
  #open = true;
  readonly name: string;
  constructor(name: string, fail = false) {
    if (fail) throw new Error(`cannot open ${name}`);
    this.name = name;
    log.push(`open ${name}`);
  }
  query(sql: string): string {
    if (!this.#open) throw new Error(`${this.name} is closed`);
    return `${this.name}: ${sql}`;
  }
  [Symbol.dispose](): void {
    if (!this.#open) return; // idempotent: safe to dispose twice
    this.#open = false;
    log.push(`close ${this.name}`);
  }
}

// using: each resource is disposed when the block exits, in reverse order,
// whether it returns or throws.
function report(): string {
  using primary = new Connection('primary');
  using replica = new Connection('replica');
  return `${primary.query('select 1')} | ${replica.query('select 2')}`;
} // replica closes, then primary

// Ownership transfer: a DisposableStack owns the resources while they are acquired.
// If a later step throws, the stack releases what it already holds; on success,
// move() hands them to a new stack that the Pair (and so its caller) owns.
class Pair implements Disposable {
  readonly primary: Connection;
  readonly replica: Connection;
  #resources: DisposableStack;
  constructor(failReplica = false) {
    using stack = new DisposableStack();
    this.primary = stack.use(new Connection('primary'));
    this.replica = stack.use(new Connection('replica', failReplica));
    this.#resources = stack.move(); // the emptied stack disposes nothing at block exit
  }
  [Symbol.dispose](): void {
    this.#resources.dispose();
  }
}

console.log(report());
{
  using pair = new Pair();
  console.log(pair.primary.query('begin'));
} // pair releases replica, then primary
assert.throws(() => new Pair(true), /cannot open replica/);

assert.deepEqual(log, [
  'open primary', 'open replica', 'close replica', 'close primary',
  'open primary', 'open replica', 'close replica', 'close primary',
  'open primary', 'close primary'
]);
console.log(log.join(', '));

In practice: implement Disposable on resource wrappers, make dispose idempotent, and declare each resource with using in the scope that owns it. A constructor or factory that acquires several resources puts them on a DisposableStack and keeps stack.move() as the owner.

Node 22 defines Symbol.dispose but has neither using nor DisposableStack. There the owner releases in try/finally, in reverse order: const c = new Connection("primary"); try { c.query("select 1"); } finally { c[Symbol.dispose](); }.

Compiled by tsc for an older target (es2023, for example), using becomes try/finally helper code; DisposableStack still needs the runtime or a polyfill.

With using, a disposal error while another error is in flight is reported as a SuppressedError holding both.

Do not rely on FinalizationRegistry for release: callbacks run late or never.