Optional Chaining in JavaScript

Introduction to ES6 feature Optional chaining

ยท

3 min read

Optional chaining is a handy feature introduced in ES2020 that allows you to safely access nested properties on an object without having to check if each reference in the chain is valid. This helps avoid pesky errors like cannot to read property 'x' of undefined. Let's take a look at what optional chaining is and how you can use it in your code.

What is Optional Chaining?

Optional chaining uses the ?. operator to access a property on an object only if that object is not null or undefined. If the object is nullish, it will short-circuit and return undefined instead of throwing an error.

For example:

const user = {
  name: 'John'
};

const userName = user?.name; // John
const userAge = user?.age; // undefined

This allows us to safely access the name property since the user is defined. But age does not exist, so it returns undefined instead of throwing an error.

Optional Chaining for Function Calls

We can also use optional chaining to conditionally call functions that may not exist.

const user = {
  logName() {
    console.log('User name is John');
  }
}

user?.logName(); // Logs 'User name is John'

user.logAge?.(); // Does nothing, no error thrown

The function will only be called if the user object exists and the logName method is defined.

Comparing Optional Chaining to Other Approaches

To see why optional chaining is useful, let's compare it to some common alternatives.

Without optional chaining, we have to check if a user is null before accessing the name:

if (user != null) {
  user.name; 
}

Or use the && operator for short-circuit evaluation:

user && user.name;

These approaches work but optional chaining is much more concise and improves readability.

Using Optional Chaining in a React Application

Optional chaining can be useful in React applications when accessing nested properties in state or props.

For example, we may have a User component that takes a user object as a prop:

<User user={user} />

Inside the User component, we want to display the user's name:

function User({ user }) {
  return <div>{user.name}</div>
}

This would throw an error if user is undefined. We can use optional chaining to display a fallback if user does not exist:

function User({ user }) {
  return <div>{user?.name || 'Guest'}</div> 
}

Now if the user prop is missing, we gracefully render 'Guest' instead of crashing.

Optional chaining improves code readability by making it clear at the call site that the property may not exist. When using if statements or && to check for null values, it obscures the conditional logic.

With optional chaining, we immediately see that user.name may evaluate to undefined based on the ?. syntax. Our code becomes more explicit about handling potentially missing values.

In contrast, with && or if statements, the conditional check happens separately from where the property is accessed. This indirection makes the code harder to understand at a glance. Optional chaining makes the null check right where it matters most.

Browser Support

Optional chaining has good browser support but does not work in Internet Explorer. Babel can be used to transpile code down to ES5 to work in all browsers.

Conclusion

Optional chaining is a great way to avoid those pesky type errors when accessing nested properties on an object. It makes our code shorter and easier to reason about. Give it a try the next time you want to safely access a nested value!

Did you find this article valuable?

Support Mikey by becoming a sponsor. Any amount is appreciated!

ย