JavaScript

Read optional nested values safely

Optional chaining stops a property access when the value immediately to its left is null or undefined. It helps read partially populated records without nested defensive conditionals.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const account = {profile: null};
console.log(account.profile?.settings?.theme ?? "system");
const other = {profile: {settings: {theme: "dark"}}};
console.log(other.profile?.settings?.theme ?? "system");

How it works

The first chain returns undefined when profile is null, then the nullish fallback supplies system. The second chain reaches dark. Keep the optional chain continuous where each level can be absent; grouping part of it can make a later ordinary access throw.

Limits and mistakes

Optional chaining does not validate a value’s type or catch errors thrown by a getter. It also cannot make an undeclared root variable safe. Use it for expected absence, not to hide a broken data contract.

Check the result

Expect system and dark. Try a missing profile and an explicitly false field if your real data permits booleans. Decide which absences should trigger an error instead of a fallback.

Sources

Reference documentation for the behavior used in this guide: