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. Use ?[ for indexing — the parser expects a name after ?..
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. For maps, extra keys are ignored and missing fields are bound to null; for lists, positions past the end of the value list are left unbound.
Anonymous functions
let inc = function(x) { return x + 1 }
let evens = filter(function(x) { return x % 2 == 0 }, xs)
Anonymous functions are expressions, not declarations — pass them as the callback to map or filter; sort_by takes a field name and an optional reverse flag, not a callback.
Worked example: defensive-by-default config load
function 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
- Find a nested config access in your own code with three or more null checks; rewrite it with
?.and??. - Destructure a list of pairs into names in your inner loop instead of indexing by position.
- Convert one string-switch callback into a
matchwhose arms use?.on the payload.
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.