PeaBox Lab › PeaLang › Learn › Chapter 27 › Lesson 2

Part V — The Modern Experience Layer · Chapter 27 · Lesson 2 of 3

Optional chaining, null coalescing and destructuring

Null handling was the single most common source of noisy defensive code in pre-1.0 PeaLang. Three additions fixed that.

Optional chaining

let city = user?.profile?.city       # null if any link is missing
let label = handler?.()               # call only if handler is set
let first = arr?.[0]                  # index only if arr is non-null

Optional chaining short-circuits the whole chain on the first null and yields null — no exception, no half-evaluated work. It works for member access, calls and indexing, and the links compose: resp?.data?.items?.[0]?.id is one expression, not four checks.

Null coalescing

let name = user?.name ?? "anonymous"
let retries = config.retries ?? 3

?? yields the left side unless it is null. It pairs with ?. into the idiomatic default-value pattern: user?.profile?.city ?? "no city on file". Note that ?? is not or: 0 ?? 1 is 0, and "" ?? "x" is the empty string — falsy is not null.

Destructuring in let and for

let [a, b] = pair
let {name, role} = user

for [k, v] in pairs {
  print k + " = " + v
}

Destructure maps and lists at binding time. Extra keys are ignored; missing required names surface as nulls — which is why ?? usually appears alongside destructuring.

Anonymous functions

let inc = function(x) { return x + 1 }
let evens = filter(xs, function(x) { return x % 2 == 0 })

Anonymous functions are expressions, not declarations — pass them to map, filter, sort_by and pipe without inventing names.

Worked example: defensive-by-default config load

fn load_config(raw) {
  let cfg = raw ?? {}
  let host = cfg?.database?.host ?? "localhost"
  let port = cfg?.database?.port ?? 5432
  let pool = cfg?.pool?.size ?? 10
  return { "db": { "host": host, "port": port, "pool": pool } }
}

One pass, no branches, no try/catch. Each default is visible at the exact line that consumes it — the failure mode you were defending against sits at the read site, not three files away.

Guided practice

Rule of thumb. The count of if (x == null) checks in a function should trend toward zero as you adopt these operators. If it didn't, you wrote a branch in disguise where ?? belonged.

← Previous Next →