Optional chaining (?.) is a powerful JavaScript feature that safely accesses nested object properties or calls methods without causing runtime errors if a reference is null or undefined.

💡 What Optional Chaining Does
It short-circuits property access or function calls when the value before ?. is null or undefined, returning undefined instead of throwing an error.
Key Use Cases
- Accessing deeply nested properties safely
- Calling methods only if they exist
- Accessing array elements without errors
| Without Optional Chaining | With Optional Chaining |
|---|---|
user && user.address && user.address.street |
user?.address?.street |
if (obj && obj.method) obj.method(); |
obj?.method?.(); |
arr && arr[0] |
arr?.[0] |
⚠️ Important Details
Optional chaining only checks for null or undefined. If a property exists but is falsy (like false or 0), it will return that value.
How Optional Chaining Works
obj?.propreturnsundefinedifobjisnullorundefined, else returnsobj.prop.obj?.[expr]safely accesses dynamic properties.func?.()callsfunconly if it’s defined.
📌 Deep Dive: Simple Optional Chaining
const user = { name: "Anna", address: { city: "NY" } };
// Accessing city safely
console.log(user?.address?.city); // "NY"
// Accessing a missing property safely
console.log(user?.contact?.email); // undefined, no error
// Calling a method safely
const person = {
greet() { return "Hello"; }
};
console.log(person.greet?.()); // "Hello"
console.log(person.farewell?.()); // undefined, no error
undefined
"Hello"
undefined
💡 Why Use Optional Chaining?
It reduces the need for repetitive if checks and makes code cleaner and more readable, especially when working with complex or uncertain data structures.
Limitations
- Does not protect against non-object types (e.g., accessing properties on numbers).
- Cannot be used to assign values (e.g.,
obj?.prop = valuewill throw an error).
⚠️ Optional Chaining and Assignment
You cannot use optional chaining on the left side of an assignment. To safely assign a nested property, check existence first.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What does obj?.prop return if obj is null?
Question 2 of 2
Which of the following is NOT a valid use of optional chaining?
Loading results...