← Back to JavaScript Course | Chapter 5: ES6+ Features | Lesson 4 of 12

JS Optional Chaining

Basic Optional Chaining

The optional chaining operator ?. reads a property only if everything before it isn't null or undefined, returning undefined instead of throwing an error when a link in the chain is missing.

Example: Basic Optional Chaining

javascript
const user = {};
console.log(user?.name); // undefined, no error

Nested Properties

Optional chaining is especially useful for deeply nested data, like user?.address?.city, where any one of user, address, or city might not exist yet, avoiding a long chain of manual null checks before every property access.

Example: Nested Properties

javascript
const user = { address: {} };
console.log(user?.address?.city); // undefined

Optional Method Calls

?. also works before a function call, as in obj.method?.(), so the call is skipped safely if the method doesn't exist, instead of throwing a TypeError — useful for optional callbacks that might not have been provided.

Example: Optional Method Calls

javascript
const obj = {};
console.log(obj.greet?.()); // undefined, skipped safely

Optional Array Access

The same operator works with array-style access using ?.[index], letting you safely read an item from an array that might itself be null or undefined, without first checking the array's existence separately.

Example: Optional Array Access

javascript
const data = null;
console.log(data?.[0]); // undefined

Optional Chaining Limits

Optional chaining only guards against null and undefined, it does not silently swallow other kinds of errors, so code still needs normal error handling for genuine bugs.

Example: Optional Chaining Limits

javascript
const user = null;
try {
  console.log(user.name.length); // still throws, unrelated bug
} catch (e) {
  console.log("Error:", e.message);
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.