What does optional chaining (?.) do in JavaScript?
Written by Jatin Thacker, Automation Architect · Updated
?., reads a property or calls a method only if the thing before it is not null or undefined. If it is, the whole expression stops and returns undefined instead of throwing a TypeError.This answer is one piece of Chapter 4: Arrays and Objects.
API responses and test data are often nested, and not every record has every level. A pending order has no shipment yet, so reading order.shipment.courier.name on it crashes the test with Cannot read properties of undefined. Optional chaining makes that read safe.
In the example, shipped.shipment?.courier?.name reads BlueDart as normal. On pending, shipment is undefined, so ?. stops there and the expression returns undefined. The try block shows what happens with plain dots on the same object: a TypeError.
Pair it with ?? to give a fallback. pending.shipment?.courier?.name ?? 'not assigned' returns the courier's name when there is one and not assigned when there is not. ?? only steps in for null and undefined, so a real 0 or empty string is kept.
It also works with brackets and calls: orders?.[0]?.id is safe when orders is null, and pending.cancel?.() calls the method only if it exists.
Use it for data that may genuinely be missing. In a check that a field must be present, a crash is the right result, so assert on the value instead of hiding the gap.
const shipped = { id: 'ORD-4100', shipment: { courier: { name: 'BlueDart' } } };
const pending = { id: 'ORD-4101' };
console.log(shipped.shipment?.courier?.name);
console.log(pending.shipment?.courier?.name);
try {
console.log(pending.shipment.courier.name);
} catch (err) {
console.log(err.constructor.name + ':', err.message);
}
console.log(pending.shipment?.courier?.name ?? 'not assigned');
const orders = null;
console.log(orders?.[0]?.id);
console.log(pending.cancel?.());BlueDart undefined TypeError: Cannot read properties of undefined (reading 'courier') not assigned undefined undefined
{ id: 'ORD-4101' }. What does order.shipment?.awb return?Related questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free