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

JS Optional Chaining

Optional chaining lets you look deep inside something without crashing if a part is missing, like checking a cupboard and stopping politely if it is empty. You get undefined instead of an error.
Syntax
javascript
object?.property
object?.[key]
object.method?.()

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.

उदाहरण: 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.

उदाहरण: 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.

उदाहरण: 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.

उदाहरण: 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.

उदाहरण: Optional Chaining Limits

javascript
const user = null;
try {
  console.log(user.name.length); // still throws, unrelated bug
} catch (e) {
  console.log("Error:", e.message);
}
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

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.