Emmanuel Akinfulubi

JavaScriptBasic

Read nested properties with optional chaining in JavaScript

Beginner · 3 min read

Real data has gaps. A trip record might have a passenger, or not yet. The passenger might have contact details, or not. If you write trip.passenger.contact.phone and any step along the way is missing, JavaScript throws an error and your page stops working. Optional chaining, written ?., lets you read down a chain like that safely.

In this tutorial you will read a passenger's phone number from three trip records: a complete one, one with no passenger, and one with a passenger but no contact details. You will see exactly what ?. protects, and the case where one ?. is not enough. You need to know what objects and nested objects are.

Why the error happens

Reading a property of an object that doesn't have it is fine. You get undefined. Reading a property of undefined is not:

JavaScript

const empty = { code: 'LAG-IB-08' };
console.log(empty.passenger); // undefined

That line is fine. But empty.passenger.name asks for .name of undefined, and that throws a TypeError. In a long chain, the error comes from the step after the missing one.

What ?. does

a?.b checks a first. If a is null or undefined, the whole expression stops right there and gives undefined. Otherwise it reads a.b as normal.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

99 Optional chaining down a record that may be empty

easy

Read a passenger's phone number out of a trip record where the passenger, and their contact details, may be missing. Use ?., then show a chain where one ?. is not enough.

Stuck? Three hints, smallest first
  1. 1. a?.b gives undefined instead of throwing when a is null or undefined.
  2. 2. Once it short-circuits, the whole rest of the chain is skipped.
  3. 3. It only guards the step it is written on, so a later step can still throw.

Step 1: three records

Step 1

const trip = {
  code: 'LAG-IB-07',
  passenger: { name: 'Adaeze', contact: { phone: '0803 000 0000' } },
  stops: ['Yaba', 'Ojota'],
};
const empty = { code: 'LAG-IB-08' };
const partial = { code: 'LAG-IB-09', passenger: { name: 'Bola' } };

trip has everything. empty has no passenger. partial has a passenger with no contact. These three cover every way the chain can be missing a piece.

Step 2: the plain chain throws

Step 2

const empty = { code: 'LAG-IB-08' };
try {
  empty.passenger.name;
} catch (err) {
  console.log(err.name); // TypeError
}

empty.passenger is undefined, and reading .name from it throws.

Step 3: add ?.

Step 3

const trip = {
  code: 'LAG-IB-07',
  passenger: { name: 'Adaeze', contact: { phone: '0803 000 0000' } },
};
const empty = { code: 'LAG-IB-08' };
console.log(trip.passenger?.name);  // Adaeze
console.log(empty.passenger?.name); // undefined

When the passenger is there, ?. behaves just like a dot. When it's missing, you get undefined instead of an error.

Step 4: one ?. skips the rest of the chain

Step 4

const empty = { code: 'LAG-IB-08' };
console.log(empty.passenger?.contact.phone); // undefined

Only the first step has ?., yet this doesn't throw. Once ?. finds undefined, it skips everything to its right. .contact and .phone are never reached. This is called short-circuiting.

Step 5: but it only guards its own step

Now the record with a passenger and no contact:

Step 5

const partial = { code: 'LAG-IB-09', passenger: { name: 'Bola' } };
try {
  partial.passenger?.contact.phone;
} catch (err) {
  console.log(err.name); // TypeError
}
console.log(partial.passenger?.contact?.phone); // undefined

This is the case that catches people. The passenger exists, so the ?. doesn't stop anything. Then contact is undefined, and the plain .phone after it throws. A ?. only checks the value directly to its left. Every step that might be missing needs its own ?..

So the safe way to read the phone is trip.passenger?.contact?.phone.

Step 6: arrays and methods

?. has two more forms. ?.[ ] is for reading by index or by a key in a variable. ?.() is for calling a method that might not exist:

Step 6

const trip = { code: 'LAG-IB-07', stops: ['Yaba', 'Ojota'] };
const empty = { code: 'LAG-IB-08' };
console.log(trip.stops?.[0]);    // Yaba
console.log(empty.stops?.[0]);   // undefined
console.log(trip.describe?.());  // undefined

trip has no describe method. Without the ?., trip.describe() would throw "is not a function". With it, you get undefined.

Step 7: a readable default with ??

undefined isn't something you want to show a user. Pair ?. with ??, which gives a fallback when the left side is null or undefined:

Step 7

const empty = { code: 'LAG-IB-08' };
console.log(empty.passenger?.name ?? 'unknown'); // unknown

The full solution

The answer panel has all three records, shows the plain chain throwing, the short-circuit, the partial record that still throws with one ?., the index and method forms, and the ?? default. Press Run to see the output.

The answer

const trip = {
  code: 'LAG-IB-07',
  passenger: { name: 'Adaeze', contact: { phone: '0803 000 0000' } },
  stops: ['Yaba', 'Ojota'],
};

const empty = { code: 'LAG-IB-08' };                 // no passenger at all
const partial = { code: 'LAG-IB-09', passenger: { name: 'Bola' } };   // no contact

let plainThrew = '';
try {
  empty.passenger.name;
} catch (err) {
  plainThrew = err.name;
}

// passenger exists, contact does not, so .phone runs on undefined and throws.
let stillThrew = '';
try {
  partial.passenger?.contact.phone;
} catch (err) {
  stillThrew = err.name;
}

console.log('phone:', trip.passenger?.contact?.phone);
console.log('missing passenger:', empty.passenger?.contact?.phone);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a present branch reads normally', trip.passenger?.name, 'Adaeze');
test('a missing one gives undefined rather than throwing', empty.passenger?.name, undefined);
test('without the ?. it throws', plainThrew, 'TypeError');
test('once it short-circuits the rest of the chain is skipped', empty.passenger?.contact.phone, undefined);
test('but an earlier ?. does not protect a later step', stillThrew, 'TypeError');
test('the guarded version of that chain is fine', partial.passenger?.contact?.phone, undefined);
test('?.[ ] does the same for an index', empty.stops?.[0], undefined);
test('?.() for a method that may not be there', trip.describe?.(), undefined);
test('pair it with ?? for a readable default', empty.passenger?.name ?? 'unknown', 'unknown');

?. answers one question: is the thing on its left null or undefined? If so, the whole expression stops there and evaluates to undefined, which is why empty.passenger?.contact.phone does not throw even though .phone is unguarded — evaluation never reached it.

partial is the case that catches people. passenger exists, so the chain does not short-circuit; contact is undefined; and the unguarded .phone throws. A ?. guards the step it is written on, so every step that might be missing needs its own. Two limits worth knowing: ?. cannot be used on the left of an assignment, and it says nothing about a key existing — a genuine undefined value and a missing branch read identically, which is what Object.hasOwn (exercise 84) is for. Reach for ?? 'default' at the end rather than leaving undefined to travel further.

Common mistakes

  • Putting one ?. at the start and expecting the whole chain to be safe. It only guards the step it is on.
  • Using ?. everywhere. If a value must always be there, a plain dot that throws tells you about the bug sooner.
  • Assigning through ?.. trip.passenger?.name = 'x' is a syntax error. Optional chaining is only for reading.

Try it yourself

  1. Write phoneOf(trip) that returns the phone or 'no phone' for all three records.
  2. Read the last stop safely with trip.stops?.at(-1), and try it on empty.
  3. Add a describe() method to trip that returns its code, then call trip.describe?.() again.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.