Optional Chaining
Learn Optional Chaining
Optional chaining (?.) reads a property or calls a function only if the value to its left is not null or undefined.
In this lesson, you will study the rule, run a complete TypeScript example, explain its output, and test a small change.
What you’ll learn
- Explain the main rule behind optional chaining.
- Predict the result of the complete runnable TypeScript example.
- Recognize one common mistake and correct it.
Understand the concept
It reduces verbose null checks for optional structures. If an intermediate value is missing, the chain evaluates to undefined rather than attempting the access. Optional chaining is not a fallback operator; combine it with ?? if you want a default value.
See the concept visually
Use the diagram to locate the checks, values or branches involved in the example.
Run a complete TypeScript example
Save this code as main.ts or paste it into the TypeScript Playground. The example uses fixed values so it runs without prompting for input.
TypeScript code
type Person = { profile?: { city: string } };
const person: Person = {};
console.log(person.profile?.city ?? "City unknown");
const other: Person = { profile: { city: "Chennai" } };
console.log(other.profile?.city ?? "City unknown");Verified output
City unknown
ChennaiHow to run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. When using a project configuration, run the matching project build instead.
Trace the execution
The first person has no profile, so ?. yields undefined and ?? supplies the fallback. The second has a profile, so the city is printed.
Predict the output before you run the sample. Compare each line with the source expression that produced it, and distinguish the type checker’s work from what happens in JavaScript at runtime.
Common mistakes and how to avoid them
An optional chain guards only the portion written with ?. and does not ensure that a present string is valid or nonempty.
Debugging habit: when a change is rejected, read the exact compiler diagnostic and inspect the operand types. When it compiles but behaves unexpectedly, follow the values through the JavaScript expressions.
Practice it yourself
Add an optional pin property inside profile and print it with a fallback. Try pin = 0 and confirm ?? retains zero.
Challenge: write down your prediction first, run the changed source, and explain any difference. Return to the verified version before continuing.
Check your understanding
Review the key idea
Optional Chaining: It reduces verbose null checks for optional structures.
Optional chaining short-circuits nullish property access.
Before continuing, be able to explain what is checked before execution and what actually changes at runtime in the example above.
Reaching the recap and completing the quizzes are separate milestones.