In the Objects chapter we saw that objects can contain other objects, and that we reach nested values with a chain of dots like student.address.city.
That works perfectly, as long as every link in the chain exists. But real data is often incomplete. A new user may not have filled in their address yet. An API may leave out a field. And then this happens:
const student1 = {
name: "Riya",
address: {
city: "Pune"
}
};
const student2 = {
name: "Arjun"
// no address yet
};
console.log(student1.address.city);
console.log(student2.address);
console.log(student2.address.city);Output:
Pune
undefined
TypeError: Cannot read properties of undefined (reading 'city')Reading a missing property just gives undefined, which is fine. But reading a property of undefined crashes the program. This is one of the most common errors in real JavaScript apps.
Optional chaining (?.) solves this neatly. It was added in ES2020 and works in all modern browsers and Node.js 14+.
What is Optional Chaining?
The optional chaining operator
?.accesses a property, but if the value on its left isnullorundefined, it stops and returnsundefinedinstead of throwing an error.
const student1 = {
name: "Riya",
address: {
city: "Pune"
}
};
const student2 = {
name: "Arjun"
};
console.log(student1.address?.city);
console.log(student2.address?.city);Output:
Pune
undefinedRead student2.address?.city as: "If address exists, give me its city. If not, just give me undefined."
Think of it like asking a friend to pick up a parcel from the second floor, but telling them: "If the building is locked, just come back." Without that instruction, they'd stand at the locked door forever (the crash).
How It Works, Step by Step
For a?.b, JavaScript does this:
1. Evaluate a
2. Is a null or undefined?
YES → stop here, the whole expression is undefined
NO → continue normally and read a.bSo these two lines mean the same thing:
a?.b
(a === null || a === undefined) ? undefined : a.b(Except that a is only evaluated once.)
The Old Way vs the New Way
Before optional chaining, we had to check every level with &&:
const order = {
id: 101,
customer: {
name: "Meera",
contact: {
email: "meera@example.com"
}
}
};
const emptyOrder = { id: 102 };
// The old way: check every level with &&
const email1 = order.customer && order.customer.contact && order.customer.contact.email;
const email2 = emptyOrder.customer && emptyOrder.customer.contact && emptyOrder.customer.contact.email;
console.log(email1);
console.log(email2);
// The new way: optional chaining
console.log(order.customer?.contact?.email);
console.log(emptyOrder.customer?.contact?.email);Output:
meera@example.com
undefined
meera@example.com
undefinedSame result, much shorter, and you don't repeat order.customer three times.
The Three Forms of ?.
Optional chaining works for normal property access, bracket access, and function calls:
Form | Meaning |
|---|---|
| Read |
| Bracket access, for dynamic keys and array indexes |
| Call |
const user = {
name: "Kabir",
skills: ["JavaScript", "SQL"],
greet() {
return "Hi, I am " + this.name;
}
};
const guest = null;
// 1. Property access: obj?.prop
console.log(guest?.name);
// 2. Bracket access: obj?.[expression]
const key = "name";
console.log(user?.[key]);
console.log(guest?.[key]);
// Works with arrays too
console.log(user.skills?.[0]);
console.log(user.projects?.[0]);
// 3. Function / method call: fn?.()
console.log(user.greet?.());
console.log(user.sayBye?.());Output:
undefined
Kabir
undefined
JavaScript
undefined
Hi, I am Kabir
undefinedNotice the bracket form is ?.[, not ?[, and the call form is ?.(, not ?(. The dot is always there. (A plain ? would be confused with the ternary operator a ? b : c.)
user.sayBye?.() means: "call sayBye if it exists, otherwise skip it". This is handy for optional callbacks:
const button = {
label: "Save",
onClick: null // no handler attached yet
};
function handle(component) {
component.onClick?.();
console.log(component.label + " handled");
}
handle(button);
button.onClick = () => console.log("Saving...");
handle(button);Output:
Save handled
Saving...
Save handledOnly null and undefined Stop the Chain
This is the most important detail. ?. does not care about other falsy values like 0, "" or false. Those are real values and the chain continues:
const data = { price: 0, title: "", inStock: false, discount: null };
console.log(data?.price);
console.log(data.title?.length);
console.log(data.discount?.percent);Output:
0
0
undefineddata.title is an empty string, which is not null/undefined, so .length is read and gives 0. Only data.discount (which is null) stops the chain.
This is a real difference from the old && trick, which stops at any falsy value:
const s = "";
console.log(s && s.length); // stops at "" and returns ""
console.log(s?.length); // "" is a real string, so returns 0Output (the first line is an empty string):
0Short-Circuiting: The Rest of the Chain Is Skipped
When ?. finds null or undefined, it doesn't just skip the next step. It skips everything to its right in the same chain. Even function calls inside the skipped part never run:
let calls = 0;
function getIndex() {
calls++;
return 0;
}
const list = null;
console.log(list?.[getIndex()]);
console.log("getIndex was called " + calls + " times");
const person = null;
console.log(person?.address.city.pin);Output:
undefined
getIndex was called 0 times
undefinedIn person?.address.city.pin, since person is null, the whole chain .address.city.pin is skipped, so there is no error even though we used plain dots after the ?..
But ?. Only Protects One Spot
Short-circuiting only helps when the value right before ?. is missing. If person exists but address doesn't, the plain dot after it still crashes:
const person = { name: "Zoya" };
console.log(person?.address.city);Output:
TypeError: Cannot read properties of undefined (reading 'city')person?.address.city
person → { name: "Zoya" } exists, so ?. continues
.address → undefined
.city → reading a property of undefined → TypeErrorPut ?. exactly where a value may be missing: person?.address?.city.
Parentheses Break the Chain
Wrapping part of the chain in parentheses ends the short-circuit at the closing bracket:
const person = null;
console.log((person?.address).city);Output:
TypeError: Cannot read properties of undefined (reading 'city')(person?.address) becomes undefined, and then .city is read from undefined outside the protected chain.
Optional Chaining + Nullish Coalescing
Optional chaining gives undefined when something is missing. Usually you want a sensible default instead. That's exactly what the nullish coalescing operator ?? from the Operators chapter does. They are a perfect pair:
const settings = {
theme: {
fontSize: 0
}
};
const noSettings = {};
console.log(noSettings.theme?.color ?? "light");
console.log(settings.theme?.fontSize ?? 16);
console.log(settings.theme?.fontSize || 16);Output:
light
0
16The last line shows why ?? is the better partner: with ||, a real setting of 0 is thrown away and replaced by 16.
A Practical Example: Handling API Data
Data from a server often has missing fields. Here's a list of students where some profiles are incomplete:
const apiResponse = {
users: [
{ name: "Aisha", profile: { college: "IIT Delhi", cgpa: 8.9 } },
{ name: "Rohan", profile: { college: "NIT Trichy" } },
{ name: "Neha" }
]
};
for (const user of apiResponse.users) {
const college = user.profile?.college ?? "Not provided";
const cgpa = user.profile?.cgpa ?? "N/A";
console.log(user.name + " | " + college + " | " + cgpa);
}
console.log(apiResponse.users[5]?.name ?? "No such user");
console.log(apiResponse.admins?.length ?? 0);Output:
Aisha | IIT Delhi | 8.9
Rohan | NIT Trichy | N/A
Neha | Not provided | N/A
No such user
0No crashes, and every missing value gets a clear default. apiResponse.users[5] doesn't exist (the array has only 3 items), so ?.name safely returns undefined.
Things Optional Chaining Can't Do
1. You Can't Assign with It
const profile = {};
profile?.name = "Dev";Output:
SyntaxError: Invalid left-hand side in assignment?. is for reading. To write, make sure the object exists first.
2. It Doesn't Help with Undeclared Variables
console.log(notDeclared?.name);Output:
ReferenceError: notDeclared is not defined?. handles a variable whose value is null or undefined. It doesn't help if the variable was never declared at all.
3. It Doesn't Check the Type
fn?.() only skips the call when fn is null or undefined. If the property exists but is not a function, you still get an error:
const user = { greet: "hello" };
user.greet?.();Output:
TypeError: user.greet is not a function. vs ?. vs &&
Expression | When | When | When |
|---|---|---|---|
|
| Reads | Reads |
|
| Reads | Reads |
|
|
| Reads |
Don't Overuse It
It's tempting to put ?. everywhere "just in case". Don't. If a value must exist, a crash is actually useful: it tells you something is wrong right where it happened.
// Every order MUST have an id. Hiding a missing id hides a real bug.
console.log(order?.id?.toString?.()); // too defensive
// Only the optional part gets ?.
console.log(order.id + " → " + (order.coupon?.code ?? "no coupon"));Use ?. for data that is genuinely optional, not to silence errors you don't understand.
Common Mistakes
Writing
obj?[key]orfn?(). The correct forms areobj?.[key]andfn?.().Expecting
?.to protect the whole chain.a?.b.cstill throws ifaexists buta.bisundefined. Add?.at each optional level.Using it on the left side of
=. That's aSyntaxError.Pairing it with
||instead of??.||also replaces valid values like0and"".Expecting
nullback. Even if the missing value wasnull,a?.breturnsundefined.Overusing it and hiding bugs in data that should always be present.
Interview Tips
A good short answer to "What is optional chaining?":
"Optional chaining,
?., was added in ES2020. It reads a property, index or calls a function only if the value on its left is notnullorundefined; otherwise the whole expression short-circuits toundefinedinstead of throwing aTypeError. It's usually combined with??to provide a default."
Common follow-ups:
"Difference between
a?.banda && a.b?"?.only stops onnull/undefinedand returnsundefined;&&stops on any falsy value and returns that value."What does
null?.a.b.creturn?"undefined, because short-circuiting skips the whole rest of the chain."What does
(null?.a).bdo?" Throws aTypeError; parentheses end the chain."Can you assign with
?.?" No, it's aSyntaxError.
Practice: given const company = { ceo: { name: "Anita" }, employees: [] }, predict company.ceo?.name, company.cto?.name, company.employees[0]?.name ?? "none", company.cto.name and company.getRevenue?.().
Conclusion
Optional chaining (?.) lets you safely read nested data that might be missing.
If the value before
?.isnullorundefined, the expression returnsundefinedinstead of crashing.It has three forms:
obj?.prop,obj?.[key]andfn?.().Only
nullandundefinedstop the chain;0,""andfalsedon't.It short-circuits: everything to its right in the chain is skipped.
Combine it with
??for clean defaults.It can't be used for assignment, and shouldn't be used to hide real bugs.
In the next chapter, we'll look at more built-in Object methods for working with objects and their properties.