Optional Chaining

2025-06-09

Today I learned, thanks to this blogpost, that Javascript allows for optional chaining.

That means that instead of writing code like this:

if (user && user.profile && user.profile.avatar) {
  console.log(user.profile.avatar);
}

You can write it like this:

console.log(user?.profile?.avatar);

The question mark indicates that the item may not exist. If user or user.profile or user.profile.avatar returns undefined it will just return that directly without the need to chain predicates together with &&.

This is very neat! Thanks to Matt Smith for writing it down!