Optional Chaining
What is optional chaining
Accesses an object's property or calls a function.
- If an object accessed or function called using this operator is undefinedornull.
- The expression short circuits, evaluates to undefinedinstead of throwing an error.
const adventurer = { name: 'Alice', cat: { name: 'Dinah', }, }; const dogName = adventurer.dog?.name; console.log(dogName); // undefined console.log(adventurer.someNonExistentMethod?.()); // undefined
Result is a shorter expression when accessing chained properties when the possibility exists that a reference may be missing.
const nestedProp = obj.first && obj.first.second; // equivalent const nestedProp = obj.first?.second;
The value of obj.first is confirmed to be non-null before accessing the value of obj.first.second.
- This prevents the error that would occur if you accessed obj.first.seconddirectly without testingobj.first.