Basic Property Access with ?.
What you'll learn: How to safely access object properties that might not exist without causing runtime errors.
The Problem With Traditional Property Access
Before optional chaining, accessing a nested property on an object that might be undefined or null would crash your code:
const user = null;
const name = user.name; // ❌ TypeError: Cannot read property 'name' of null
You had to write defensive checks:
const name = user && user.name; // Verbose and clunky
How ?. Solves This
The optional chaining operator (?.) short-circuits when it encounters null or undefined, returning undefined instead of throwing an error:
const user = null;
const name = user?.name; // ✅ Returns undefined, no error!
Think of ?. as asking a polite question: "Does this exist? If yes, give me the property. If no, just return undefined and move on."
Basic Usage
const user = { name: 'Alice' };
console.log(user?.name); // 'Alice'
console.log(user?.age); // undefined (property doesn't exist)
const empty = null;
console.log(empty?.anything); // undefined (object is null)
const missing = undefined;
console.log(missing?.prop); // undefined (object is undefined)
Why This Matters
You avoid writing repetitive null checks and make your code cleaner and safer. It's especially useful when dealing with API responses, configuration objects, or any data structure where properties might be missing.
Key Takeaway: Use ?. to safely access properties on objects that might be null or undefined — it returns undefined instead of throwing an error, eliminating the need for verbose guard clauses.