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.

Paradigms: imperative, OOP & functional

How each language supports the main programming styles: step-by-step imperative code, objects with encapsulation, polymorphism and composition, and functional programming with pure functions, immutability, higher-order functions and algebraic data types. Most real programs mix them; each entry names when a style fits.

Imperative & procedural programming: statements, loops, mutation, procedures

TypeScript

Imperative code is a sequence of statements that change state: declare a variable, loop, update it, return it. Procedural programming organises those steps into named functions that take inputs and return results. JavaScript is imperative at heart (let, for...of, Map.set), with functional array methods layered on top; TypeScript adds types but no new control flow.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Order = { readonly category: string; readonly cents: number };

const orders: Order[] = [
  { category: 'books', cents: 1200 },
  { category: 'games', cents: 5999 },
  { category: 'books', cents: 850 },
  { category: 'music', cents: 999 },
  { category: 'games', cents: 2000 }
];

// A procedure: local mutable state, updated step by step, returned at the end.
function totalsByCategory(list: readonly Order[]): Map<string, number> {
  const totals = new Map<string, number>();
  for (const order of list) {
    const current = totals.get(order.category) ?? 0; // missing key: start at 0
    totals.set(order.category, current + order.cents);
  }
  return totals;
}

function formatCents(cents: number): string {
  return `$${(cents / 100).toFixed(2)}`;
}

let grand = 0;
for (const [category, cents] of totalsByCategory(orders)) {
  console.log(`${category.padEnd(6)} ${formatCents(cents)}`);
  grand += cents;
}
console.log(`total  ${formatCents(grand)}`);

In practice: keep mutation local to one function and return the result instead of updating module-level variables; use readonly parameter types so a procedure cannot change its caller's data; reach for a plain loop when it is clearer than a chain of reduce calls.

Money is kept in integer cents: adding floating-point dollars (0.1 + 0.2) drifts.

readonly Order[] stops the procedure from pushing to or sorting the caller's array, but the objects inside are still mutable unless their fields are readonly too.

A Map iterates in insertion order, so the output follows the order categories first appear.

Objects & encapsulation: classes, struct methods, impl blocks, class invariants

TypeScript

A TypeScript class bundles data with the methods that keep it valid. #field is a JavaScript private field, enforced at runtime; the private keyword is checked only by tsc and disappears in the emitted code. A get accessor exposes a read-only view, and the constructor is the one place a new object is built, so it is where the invariant is first established.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
class Account {
  readonly owner: string;
  #cents: number; // private at runtime, not only to the type checker

  constructor(owner: string, openingCents: number) {
    // The constructor establishes the invariant: a non-negative whole number of cents.
    if (!Number.isInteger(openingCents) || openingCents < 0) {
      throw new RangeError(`opening balance must be whole, non-negative cents: ${openingCents}`);
    }
    this.owner = owner;
    this.#cents = openingCents;
  }

  get balance(): number {
    return this.#cents; // read-only view of the private field
  }

  deposit(cents: number): void {
    if (!Number.isInteger(cents) || cents <= 0) throw new RangeError('deposit must be positive');
    this.#cents += cents;
  }

  withdraw(cents: number): boolean {
    if (!Number.isInteger(cents) || cents <= 0 || cents > this.#cents) return false; // keeps balance >= 0
    this.#cents -= cents;
    return true;
  }
}

const account = new Account('Ada', 5000);
account.deposit(2500);
console.log(account.withdraw(10000), account.withdraw(3000), account.balance); // false true 4500

try {
  new Account('Bob', -1);
} catch (err) {
  console.log((err as Error).message);
}
// account.#cents = 0; // compile error: #cents is not accessible outside class Account

In practice: validate in the constructor and throw on bad input, so no invalid object ever exists; keep fields #private and expose behaviour (deposit, withdraw) instead of setters; mark fields readonly when they never change.

private (the TS keyword) is erased: at runtime obj["field"] still reads it. #field cannot be reached from outside the class at all.

A getter without a setter makes balance read-only from outside, but returning a private array or object still lets callers mutate it; return a copy.

Node's type stripping does not support constructor parameter properties (constructor(private x: number)); declare fields explicitly.

Polymorphism: structural interfaces, Go interfaces, dyn Trait, virtual functions

TypeScript

Polymorphism lets one piece of code work with many types through a shared contract. In TypeScript the contract is an interface, checked structurally: any value with the right members fits, whether it is a class instance or an object literal. implements is optional and only asks tsc to check a class against the interface early. At runtime every method call is dynamic: it looks up the method on the object.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
interface Shape {
  readonly name: string;
  area(): number;
}

// implements is optional: it asks tsc to check the class against Shape here.
class Circle implements Shape {
  readonly name = 'circle';
  readonly radius: number;
  constructor(radius: number) {
    this.radius = radius;
  }
  area(): number {
    return Math.PI * this.radius ** 2;
  }
}

class Rect implements Shape {
  readonly name = 'rect';
  readonly width: number;
  readonly height: number;
  constructor(width: number, height: number) {
    this.width = width;
    this.height = height;
  }
  area(): number {
    return this.width * this.height;
  }
}

// An object literal fits too: the check is structural, not by declared name.
const square: Shape = { name: 'square', area: () => 4 };

function totalArea(shapes: readonly Shape[]): number {
  let sum = 0;
  for (const s of shapes) sum += s.area(); // each object supplies its own area
  return sum;
}

const shapes: Shape[] = [new Circle(1), new Rect(2, 3), square];
for (const s of shapes) console.log(`${s.name.padEnd(6)} ${s.area().toFixed(2)}`);
console.log(`total  ${totalArea(shapes).toFixed(2)}`);

In practice: describe what a function needs with a small interface rather than a concrete class; write implements on classes meant to satisfy it, so a drifting signature fails at the class; use a discriminated union instead when the set of variants is closed and known.

Interfaces are erased: there is no instanceof Shape at runtime. Check for a member, use a class, or add a discriminant field.

implements does not change the class's type or add methods; it only reports an error if the class does not fit.

Inheritance vs composition: extends, struct embedding, supertraits, object slicing

TypeScript

TypeScript classes support single inheritance: class B extends A reuses A's members, override replaces a method, and super.method() calls the base version. Inheritance couples the subclass to the base class's internals: if a base method calls another overridable method, a subclass that overrides both can double-count, the fragile base class problem shown below. Composition (holding an object and forwarding to it) depends only on the public API.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
class Tally {
  #count = 0;
  add(): void { this.#count++; }
  addMany(n: number): void {
    for (let i = 0; i < n; i++) this.add(); // reuses add internally: an implementation detail
  }
  get value(): number { return this.#count; }
}

// Inheritance: the subclass counts calls by overriding both methods.
class AuditedTally extends Tally {
  calls = 0;
  override add(): void {
    this.calls++;
    super.add(); // run the base behaviour too
  }
  override addMany(n: number): void {
    this.calls += n;
    super.addMany(n); // base addMany calls this.add, our override: counted twice
  }
}

// Composition: hold a Tally and forward. The inner object cannot call back into us.
class ComposedTally {
  readonly #inner = new Tally();
  calls = 0;
  add(): void {
    this.calls++;
    this.#inner.add();
  }
  addMany(n: number): void {
    this.calls += n;
    this.#inner.addMany(n);
  }
  get value(): number {
    return this.#inner.value;
  }
}

const inherited = new AuditedTally();
inherited.addMany(3);
const composed = new ComposedTally();
composed.addMany(3);
console.log('inherited', inherited.value, inherited.calls); // 3 6: the fragile base class
console.log('composed ', composed.value, composed.calls); // 3 3

In practice: favour composition over inheritance; use extends only for a true is-a relationship where the subclass can stand in anywhere the base is expected (the Liskov substitution principle); write override so renamed base methods are caught.

A subclass constructor must call super(...) before it touches this.

Turn on noImplicitOverride in tsconfig so every overriding method must say override.

Subclasses cannot reach the base's #private fields; they can reach protected ones, which is part of what makes the base fragile.

Design principles: SOLID and dependency inversion with an injected interface

TypeScript

SOLID names five design principles: Single responsibility (one reason to change per unit), Open/closed (add behaviour by adding code, not editing working code), Liskov substitution (implementations must honour the contract), Interface segregation (small, focused interfaces) and Dependency inversion (high-level policy depends on an abstraction, and the concrete detail is passed in). Below, OrderService depends on a one-method Notifier interface; main injects a fake or a console implementation through the constructor.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Interface segregation: OrderService needs exactly one capability.
interface Notifier {
  send(to: string, message: string): void;
}

// Dependency inversion: the policy depends on Notifier, not on email or SMS code.
class OrderService {
  readonly #notifier: Notifier;
  #nextId = 1;
  constructor(notifier: Notifier) {
    this.#notifier = notifier; // injected by the caller
  }
  place(customer: string, cents: number): number {
    const id = this.#nextId++;
    this.#notifier.send(customer, `order ${id} confirmed: ${cents} cents`);
    return id;
  }
}

class ConsoleNotifier implements Notifier {
  send(to: string, message: string): void {
    console.log(`to ${to}: ${message}`);
  }
}

// A fake for tests: records messages instead of sending them.
class FakeNotifier implements Notifier {
  readonly sent: string[] = [];
  send(to: string, message: string): void {
    this.sent.push(`${to} | ${message}`);
  }
}

const fake = new FakeNotifier();
const service = new OrderService(fake);
service.place('ada@example.com', 4200);
service.place('ada@example.com', 999);
console.log(fake.sent);

new OrderService(new ConsoleNotifier()).place('bob@example.com', 1500); // same policy, real detail

In practice: inject dependencies through the constructor and store them in a private field; define the interface next to the code that uses it, with only the methods it calls; build the real object graph in one place (main), not inside services.

Because typing is structural, a test can pass a plain object literal { send() {} } with no class at all.

A DI container is optional; constructor parameters are dependency injection already.

Functional programming: pure functions, functions as values, functional core

TypeScript

A pure function returns the same output for the same input and changes nothing outside itself; that makes it referentially transparent, so a call can be replaced by its result. TypeScript has first-class functions, closures and expression-friendly syntax (arrow functions, ternaries, array methods), but it does not enforce purity: any function may read globals, mutate its arguments or do I/O.

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 = { readonly subtotalCents: number; readonly loyaltyYears: number };

// Pure: the result depends only on the arguments, and nothing outside changes.
function discountPercent(years: number): number {
  if (years >= 5) return 15;
  if (years >= 2) return 5;
  return 0;
}

function totalCents(order: Order): number {
  return Math.round((order.subtotalCents * (100 - discountPercent(order.loyaltyYears))) / 100);
}

const formatCents = (cents: number): string => (cents / 100).toFixed(2);

// Testing a pure function is just input and expected output: no setup, no mocks.
assert.equal(totalCents({ subtotalCents: 10_000, loyaltyYears: 5 }), 8_500);
assert.equal(totalCents({ subtotalCents: 10_000, loyaltyYears: 0 }), 10_000);

// Referential transparency: a call can be swapped for its result, so caching it is safe.
const repeat: Order = { subtotalCents: 8_000, loyaltyYears: 3 };
const cached = totalCents(repeat);

// Imperative shell: reading input and printing happen here, at the edge.
const orders: Order[] = [
  { subtotalCents: 12_000, loyaltyYears: 1 },
  { subtotalCents: 8_000, loyaltyYears: 3 },
  { subtotalCents: 20_000, loyaltyYears: 6 },
];
orders.forEach((order, i) => console.log(`order ${i + 1}: ${formatCents(totalCents(order))}`));
console.log('cached equals recomputed:', cached === totalCents(repeat));

In practice: keep business rules in small pure functions that take plain data and return new data. Push I/O, clocks and randomness to the edge of the program (functional core, imperative shell). Mark inputs readonly so the compiler catches accidental mutation.

Hidden side effects are the usual way purity breaks: Date.now(), Math.random(), a module-level cache or mutating an argument array with sort() or push().

Purity is a convention in TypeScript, not a checked property; a function typed (x: number) => number can still log, throw or write globals.

Immutability: readonly and spread, value copies, let vs let mut, const

TypeScript

const stops a name from being reassigned but leaves the object behind it mutable. Compile-time immutability comes from readonly properties, Readonly<T>, readonly arrays and as const; Object.freeze adds a shallow runtime lock. Updates are written as new values with spread syntax, which copies one level and shares everything nested.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Account = Readonly<{ id: string; balance: number; tags: readonly string[] }>;

const original: Account = { id: 'a1', balance: 100, tags: ['new'] };
// original.balance = 50;    // compile error: balance is read-only
// original.tags.push('x');  // compile error: no push on readonly string[]

// Persistent update: build a new value from the old one; the old one is untouched.
const credited: Account = {
  ...original,
  balance: original.balance + 25,
  tags: [...original.tags, 'active'],
};
console.log(original.balance, original.tags);
console.log(credited.balance, credited.tags);

// const only stops rebinding the name; the object behind it is still mutable.
const counter = { hits: 1 };
counter.hits += 1;
console.log(counter.hits);

// as const: readonly literal types, checked only at compile time.
const LEVELS = ['low', 'mid', 'high'] as const;
type Level = (typeof LEVELS)[number]; // 'low' | 'mid' | 'high'
const level: Level = 'mid';

// Object.freeze: a runtime lock, but shallow; nested objects stay writable.
const config = Object.freeze({ limit: 10, stats: { reads: 0 } });
config.stats.reads += 1;
console.log(level, Object.isFrozen(config), Object.isFrozen(config.stats), config.stats.reads);

In practice: type shared data as Readonly and update it with spread, copying each nested level you change. Mutate freely inside a function on values you just created. Use Object.freeze only where runtime protection matters, since it is shallow.

Readonly<T> is shallow too: Readonly<{ tags: string[] }> still allows tags.push(); declare nested arrays as readonly string[].

readonly is erased at compile time; a value typed readonly can be mutated through another reference typed without it.

Spread copies one level, so { ...a }.nested is the same object as a.nested.

Higher-order functions: map/filter/reduce, currying, composition, returning closures

TypeScript

A higher-order function takes a function as an argument or returns one. Arrays build in the common ones (map, filter, reduce, some, every, toSorted), arrow functions make currying cheap to write, and bind gives partial application. There is no built-in compose or pipe; it is a one-line reduce.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// pipe: run functions left to right, feeding each result into the next.
const pipe =
  <T>(...fns: Array<(x: T) => T>) =>
  (x: T): T =>
    fns.reduce((acc, fn) => fn(acc), x);

// Currying: each call fixes one argument and returns a function for the rest.
const multiplyBy = (factor: number) => (n: number) => n * factor;
const add = (amount: number) => (n: number) => n + amount;

function clamp(min: number, max: number, n: number): number {
  return Math.min(max, Math.max(min, n));
}
// Partial application: bind fixes the leading arguments (typed under --strict).
const toPercent = clamp.bind(null, 0, 100);

const score = pipe(multiplyBy(10), add(5), toPercent);
console.log([3, 8, 12].map(score));

// map, filter and reduce are higher-order: they take the per-item step as an argument.
const prices = [12, 40, 7, 25];
const total = prices
  .filter((p) => p >= 10)
  .map(multiplyBy(3))
  .reduce((sum, p) => sum + p, 0);
console.log(total);

// Returning a wrapped function: a small decorator that keeps the wrapped signature.
function logged<A extends unknown[], R>(name: string, fn: (...args: A) => R) {
  return (...args: A): R => {
    const result = fn(...args);
    console.log(`${name}(${args.join(', ')}) = ${String(result)}`);
    return result;
  };
}
logged('clamp', clamp)(0, 10, 42);

In practice: use array methods for transformations and named small functions for the steps. Curry only where you really reuse the partially applied function. Type generic wrappers with rest parameters (...args: A) so they keep the wrapped signature.

Passing a function with optional parameters straight to map can surprise you: ["1","2","3"].map(parseInt) gives [1, NaN, NaN] because map also passes the index.

Each chained array method allocates a new array; for very large data a single loop or an iterator helper avoids the intermediates.

Algebraic data types: discriminated unions, type switches, enum + match, std::variant

TypeScript

A product type groups fields that all exist together (an object type); a sum type is one of several shapes. TypeScript writes sum types as discriminated unions: object types that share a literal tag such as kind. Checking the tag narrows the value, and assigning the leftover case to never makes the compiler reject a switch that misses a variant.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Each member is a product type (fields that belong together); the union is the sum type.
type PaymentEvent =
  | { kind: 'authorized'; amountCents: number }
  | { kind: 'captured'; amountCents: number }
  | { kind: 'refunded'; amountCents: number; reason: string }
  | { kind: 'failed'; code: string };

function assertNever(value: never): never {
  throw new Error(`unhandled event: ${JSON.stringify(value)}`);
}

function describe(event: PaymentEvent): string {
  switch (event.kind) {
    case 'authorized':
      return `hold ${event.amountCents}`; // narrowed: amountCents is known to exist
    case 'captured':
      return `charge ${event.amountCents}`;
    case 'refunded':
      return `refund ${event.amountCents} (${event.reason})`;
    case 'failed':
      return `failed: ${event.code}`;
    default:
      return assertNever(event); // a new kind without a case is a compile error here
  }
}

function netCents(events: readonly PaymentEvent[]): number {
  let net = 0;
  for (const e of events) {
    if (e.kind === 'captured') net += e.amountCents;
    else if (e.kind === 'refunded') net -= e.amountCents;
  }
  return net;
}

const events: PaymentEvent[] = [
  { kind: 'authorized', amountCents: 5000 },
  { kind: 'captured', amountCents: 5000 },
  { kind: 'refunded', amountCents: 1200, reason: 'damaged' },
  { kind: 'failed', code: 'card_declined' },
];
events.forEach((e) => console.log(describe(e)));
console.log('net', netCents(events));

In practice: model states that cannot coexist as a union instead of one object with optional fields. Switch on the tag and end with an assertNever default. Keep the tag a string literal so it survives JSON.

Optional fields instead of a union ({ amountCents?: number; reason?: string; code?: string }) allow impossible combinations such as a failure with a refund reason; the union rules them out.

Without the never default, only a function whose return type excludes undefined catches a missing case; a switch used for side effects compiles silently.

Declarative vs imperative: loops vs pipelines, recursion vs iteration

TypeScript

Imperative code says how: a loop, a mutable accumulator, explicit indexes. Declarative code says what: filter the active users, sort by score, take three. Array methods (filter, map, toSorted, slice) make the declarative form short, and ES2023 added non-mutating versions such as toSorted and toReversed. Recursion is declarative too, but Node's V8 engine does not eliminate tail calls, so every recursive call uses stack.

Complete program

Complete program.

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

const users: User[] = [
  { name: 'ana', active: true, score: 82 },
  { name: 'ben', active: false, score: 97 },
  { name: 'cy', active: true, score: 91 },
  { name: 'dee', active: true, score: 64 },
  { name: 'eli', active: true, score: 88 },
];

// Imperative: spell out how, step by step, mutating local state.
const picked: User[] = [];
for (const u of users) {
  if (u.active) picked.push(u);
}
picked.sort((a, b) => b.score - a.score);
const imperative: string[] = [];
for (let i = 0; i < picked.length && i < 3; i++) imperative.push(picked[i].name);

// Declarative: describe what you want; each step returns a new array.
const declarative = users
  .filter((u) => u.active)
  .toSorted((a, b) => b.score - a.score) // ES2023: sorts a copy
  .slice(0, 3)
  .map((u) => u.name);

console.log(imperative, declarative);

// Recursion reads declaratively, but each call uses a stack frame and
// JavaScript engines do not eliminate tail calls, so very deep input overflows.
const sumTo = (n: number): number => (n === 0 ? 0 : n + sumTo(n - 1));
let total = 0;
for (let i = 1; i <= 1_000_000; i++) total += i; // iteration: constant stack
console.log(sumTo(1_000), total);

In practice: use a method chain for straightforward data transformations and a for loop when you need early exit, several results from one pass or hot-path speed. Prefer toSorted to sort on shared arrays. Use iteration for recursion that could go thousands deep.

sort() mutates the array in place and returns it, so users.sort(...) inside a "declarative" chain silently reorders the caller's data.

filter followed by find-like logic scans everything; find, some and every stop at the first match.

Recursion depth limits depend on the engine and frame size; a few thousand frames is safe, a million is not.