JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 9: Modern JavaScript SyntaxLesson 43 of 150About 35 minutes

Lesson 43: Optional chaining

01Opening question

Some customers have a delivery address and some do not. How do you read the city without the program crashing for the ones who don't?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

?. stops and gives undefined when the value on its left is null or undefined.

const withAddress = { name: "Ada", address: { city: "London" } };
const without = { name: "Linus" };
console.log(withAddress.address?.city);
console.log(without.address?.city);

03Objective and prerequisites

Learning objective: Read nested properties, call methods and index arrays safely with optional chaining, and combine it with fallbacks.

You need: Lesson 38: Nested objects and arrays

Skills practised: Optional chaining.

04Explanation

Reading a property of undefined throws: user.address.city crashes when there is no address.

Optional chaining ?. checks the value on its left. If it is null or undefined, the whole expression returns undefined instead of throwing.

It works for properties (user?.name), brackets (list?.[0]) and calls (user.greet?.()).

Combine it with a fallback: user.address?.city ?? "Unknown".

05Definitions

Optional chaining
The ?. operator, which returns undefined instead of throwing when the left side is null or undefined.
Nullish
Either null or undefined.
Short-circuit
Stopping evaluation early once the result is known.

Open the full glossary

06Visual learning object

Optional chaining laboratory. Switch between objects with and without nested data and compare a plain chain with an optional chain.

Loading the interactive object…

Open the full Optional chaining laboratory page with its guided experiment.

07Examples

ex-043-01Read nested data safely Browser-executable JavaScript

?. returns undefined instead of throwing.

const orders = [
  { id: 1, delivery: { city: "Leeds" } },
  { id: 2 }
];
for (const order of orders) {
  console.log(order.id, order.delivery?.city);
}
Sample input
None
Expected output
1 Leeds 2 undefined
Common mistake
Writing order?.delivery.city, which still throws when delivery is missing.
Try this
Print "Collect in store" when there is no city.
Source
examples/ex-043-01-safe-read.js (repository pending publication)

ex-043-02Add a fallback Browser-executable JavaScript

?? supplies a value when the chain gives undefined.

const profile = { name: "Grace", social: null };
const handle = profile.social?.handle ?? "(none)";
console.log(handle);
Sample input
None
Expected output
(none)
Common mistake
Using || when an empty string handle is valid.
Try this
Give profile a social object with a handle.
Source
examples/ex-043-02-with-fallback.js (repository pending publication)

ex-043-03Optional method call Browser-executable JavaScript

?.() calls a function only if it exists.

const plugins = [
  { name: "spellcheck", init() { return "spellcheck ready"; } },
  { name: "theme" }
];
for (const p of plugins) {
  console.log(p.name, p.init?.() ?? "no init");
}
Sample input
None
Expected output
spellcheck spellcheck ready theme no init
Common mistake
Calling p.init() directly, which throws for plugins without init.
Try this
Add a third plugin with an init function.
Source
examples/ex-043-03-optional-call.js (repository pending publication)

ex-043-04Optional indexing Browser-executable JavaScript

?.[ ] reads an index only when the array exists.

const responses = [{ items: ["a", "b"] }, { items: null }];
console.log(responses[0].items?.[0]);
console.log(responses[1].items?.[0]);
console.log(responses[5]?.items);
Sample input
None
Expected output
a undefined undefined
Common mistake
Expecting ?. to protect against an index that is out of range; that already gives undefined.
Try this
Print the length of each items list, defaulting to 0.
Source
examples/ex-043-04-optional-index.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Stop the crash

Use optional chaining where data may be missing.

const users = [{ name: "Ada", manager: { name: "Grace" } }, { name: "Alan" }];
for (const u of users) {
  console.log(`${u.name} reports to ${u.manager.name}`);
}

First tag or none

Combine optional indexing and a fallback.

function firstTag(post) {
  // TODO: return the first tag, or "untagged"
}
console.log(firstTag({ tags: ["news", "js"] }));
console.log(firstTag({}));

Shipping label

Build a safe formatter for partial data.

// Write shippingLabel(order)

09Prediction

Commit to an answer first, then run the real code to compare.

const a = null;
console.log(a?.b.c.d);

What is printed?

10Debugging investigation

Optional chaining in the wrong place

The team added ?. to stop a crash for guests, but the receipt still throws a TypeError for guest orders.

const order = { id: 11, total: 18 };
const name = order?.customer.name ?? "Guest";
console.log(`Receipt for ${name}`);

More cases in the Debugging Detective Laboratory

11Practical scenario

Partial API data

Profile data arrives from several services and optional sections are often missing. Optional chaining reads those sections safely, while required fields are read normally so their absence is still noticed.

const profile = { id: 9, prefs: undefined };
const lang = profile.prefs?.language ?? "en";
console.log(profile.id, lang);

12Knowledge check

1. What is printed?

const u = {};
console.log(u.address?.city);
  • undefined
  • A TypeError
  • null
  • ""

2. What happens?

const u = {};
console.log(u?.address.city);
  • undefined is printed
  • A TypeError is thrown
  • null is printed
  • Nothing

3. Which values make ?. stop and return undefined?

  • Any falsy value
  • null and undefined
  • Only undefined
  • Empty objects

4. Why is this a SyntaxError?

const user = {};
user?.name = "Ada";
  • ?. cannot be used when assigning
  • name is reserved
  • Missing semicolon
  • user is const

5. What is printed?

const api = { ping() { return "ok"; } };
console.log(api.ping?.());
  • undefined
  • ok
  • An error
  • function

6. An order must always have an id. Which read is better?

  • order?.id?.toString()
  • order.id.toString()
  • order?.["id"]
  • String(order?.id ?? "")

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Stop the crash: Prints both lines
  • First tag or none: Prints both; Empty list; Null tags
  • Shipping label: Prints both labels; No order
  • ex-043-01: output matches the documented expected output
  • ex-043-02: output matches the documented expected output
  • ex-043-03: output matches the documented expected output
  • ex-043-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-09-modern-javascript-syntax/lesson-043-optional-chaining/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • ?. returns undefined instead of throwing when the left side is nullish.
  • Works for properties, brackets and calls.
  • Pair it with ?? for a fallback.
  • Use it only where data is genuinely optional.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation optional chaining
Context: I am learning optional chaining in JavaScript.
Task: Explain optional chaining with a customer address example, including short-circuiting.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction optional chaining drill
Context: I have practised optional chaining.
Task: Give me six snippets with ?. in different positions and ask which throw and which print undefined.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging optional chaining bug
Context: I added ?. but my code still throws TypeError: Cannot read properties of undefined.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation optional chaining practice
Context: I finished the optional chaining exercises.
Task: Create three exercises that read partial API responses safely.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review optional chaining review
Context: Here is my code that uses optional chaining.
Task: Review my code for places where ?. hides bugs and places where it is genuinely needed.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.