Objects & collections
Optional chaining ?.
Safe reading of nested properties that may be missing.
Why it exists
The most common front-end error is TypeError: Cannot read properties of undefined. It happens when code reads a property of something that isn't there: the user's profile hasn't loaded yet, an order has no address. You used to check each step by hand: user && user.profile && user.profile.avatar. ?. does the same more briefly, with no chance of forgetting a link.
Where it's used
- Server data that may arrive incomplete:
user?.profile?.avatar. - Interface state that hasn't loaded yet:
data?.items. - Optional callbacks:
options.onSuccess?.().
Syntax
object?.property
object?.[key]
function?.()Examples
const order = { id: 3 };
order.delivery?.fee; // → undefinedconst user = null;
user?.name; // → undefinedconst settings = { sound: { volume: 70 } };
settings?.sound?.volume; // → 70
settings?.video?.quality; // → undefinedconst options = {};
options.onDone?.(); // → undefinedResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
?. checks the value on its left. If it's null or undefined, evaluation of the chain stops and the result is undefined. Otherwise ?. works like a plain dot.
The whole rest of the chain stops: in a?.b.c.d, if a is null, .c and .d are never reached. But if a exists and b is undefined, .c will fail: ?. protects only the place where it stands.
There are three forms: obj?.prop, obj?.[key] for a key in a variable, and fn?.() — call the function only if it exists.
?. can't be used on the left of an assignment: user?.name = "…" is a syntax error.
Traps
How it differs from…
- The
??operator ?.and ?? are a pair: the first reads safely, the second supplies a default.
When to pick something else
Don't put ?. on every dot "just in case". If the object is guaranteed to exist (you just created or checked it), a plain dot is more honest: it shows an error right away if the guarantee is ever broken.