Optional chaining (?.)
- Version
- es2025
- Since
- es2020
- Review
- Draft
Summary#
Optional chaining returns undefined if the receiver at an optional step is null or undefined. Use it for nested values that may be absent.
Syntax#
const name = item.owner?.name;
const first = items?.[0];
onComplete?.();
Example#
function ownerLabel(item: { owner?: { name: string } }): string {
return item.owner?.name ?? "Unassigned";
}
console.log(ownerLabel({ owner: { name: "Ada" } }));
console.log(ownerLabel({}));
Expected output#
Ada
Unassigned
Common mistakes#
An optional step only checks the value immediately before it. Use another ?. if a later value can also be nullish. Parentheses that end the chain can make a later property access throw.
Version applicability#
ES2020 standardized ?.. TypeScript 3.7 added support for this syntax and can transform it when targeting older JavaScript.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0