Dung (Donny) Nguyen

Senior Software Engineer

Optional Chaining

Optional chaining in JavaScript, introduced in ES2020, is a feature that lets you safely access deeply nested properties, methods, or array elements of an object without having to check each reference in the chain for null or undefined values. If any reference in the chain is null or undefined, the entire expression short-circuits and evaluates to undefined, rather than throwing a runtime error.

The core syntax uses the ?. operator:

For example:

const user = {
  address: {
    city: "New York"
  }
};

console.log(user?.address?.city); // "New York"
console.log(user?.profile?.name); // undefined

In the above examples, attempting to access user.profile.name directly would throw an error if profile is undefined. With optional chaining, this simply returns undefined without causing an exception.

Optional chaining can also be combined with the nullish coalescing operator (??) to set default values:

const city = user?.address?.city ?? "Unknown";
console.log(city); // "New York"

It also works with functions and arrays:

user.getAddress?.().city;
usersArray?.?.name;

If any part before the ?. evaluates to null or undefined, the whole expression evaluates to undefined instead of throwing.

Best practices:

Limitations:

This feature reduces code verbosity and makes working with complex, optional data structures more robust and readable.