Optional Chaining with ?.
Safely access deeply nested properties that may be null.
The Optional Chaining Operator
Optional chaining (?.) lets you safely access a property that might be on a null or undefined value. If the value is nullish, the whole expression short-circuits to undefined instead of throwing.
type User = { profile?: { bio?: string } };
const u: User = {};
const bio = u.profile?.bio;
console.log(bio); // undefined, no crashShort-Circuiting on Nullish
When the operand before ?. is null or undefined, evaluation stops immediately and returns undefined. The rest of the chain is never executed.
const data: { value?: number } | null = null;
console.log(data?.value); // undefined, did not throwAll lessons in this course
- Optional Chaining with ?.
- Nullish Coalescing with ??
- Combining ?. and ??
- Optional Calls and Element Access