How to use optional chaining in JavaScript

Using optional chaining in JavaScript safely accesses nested object properties and methods without throwing errors when intermediate values are null or undefined. With over 25 years of experience in software development and as the creator of CoreUI, I’ve used optional chaining extensively for API response handling, configuration access, and defensive programming. From my expertise, the most reliable approach is using the ?. operator to chain property access with automatic null checking at each level. This ES2020 feature eliminates verbose null checking code while providing safe navigation through complex object structures.

Use the optional chaining operator ?. to safely access nested properties without throwing errors on null or undefined values.

const user = {
  name: 'John',
  address: {
    street: '123 Main St',
    city: 'New York'
  }
}

const street = user?.address?.street
const zipCode = user?.address?.zipCode // undefined, no error
const phoneNumber = user?.contact?.phone // undefined, no error

// Method calling with optional chaining
const result = user?.getData?.()
const length = user?.hobbies?.[0]?.length

Here user?.address?.street safely accesses the nested street property, returning undefined if any intermediate property is null or undefined. The ?.() syntax safely calls methods, and ?.[] works with bracket notation for dynamic property access. Optional chaining short-circuits at the first null or undefined value, preventing TypeError exceptions that would crash the application.

Best Practice Note:

This is the same approach we use in CoreUI components for safely accessing deeply nested configuration objects, API response data, and user-provided options. Optional chaining significantly reduces defensive coding overhead and makes code more readable while maintaining robust error handling for production applications.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team