Accesses an object's property or calls a function.
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
.
obj.first.second
directly without testing obj.first
.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