HomeAbout

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 undefined or null, the expression short circuits and evaluates to undefined instead 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.second directly without testing obj.first.

When optional chaining can backfire

Optional chaining could incorrectly return undefined in places where other data type is expected.

// a?.quantity or b?.quantity could be undefined instead of being a number, resulting in NaN error const sort = (a,b) => a?.quantity - b?.quantity

Another case is silently failing on missing attributes.

const fetchedData = data?.attribute; someFunction(fetchedData); // silently fails on missing attribute, leading to someFunction not receiving the data type it expects
AboutContact