Optional Chaining in JavaScript

In this article, we will look at a feature in JavaScript called "optional chaining."

It's a feature that makes your life easier when you're dealing with data that might not always be there.

Modern design featuring JavaScript symbols and chain links with question marks, set against a tech-oriented blue and yellow background, illustrating the concept of Optional Chaining in web development.

What is Optional Chaining?

Optional chaining (?.) is a feature in JavaScript that lets you safely access nested object properties, even if an intermediate property doesn't exist.

It prevents the common errors you'd typically get when accessing a property of undefined or null.

Screenshot of the usual typeerror a user might get that says "Uncaught TypeError: myObject.fakeMethod is not a function"

Why Use Optional Chaining?

It simplifies your code by eliminating the need for verbose and repetitive checks before safely accessing deeply nested properties.

This leads to cleaner, more readable code, especially when dealing with data that may not be fully structured or certain.

How to Use Optional Chaining

Using optional chaining in JavaScript is straightforward once you know how.

Let's look at a scenario where you have an object representing a person, and you want to access the city from their address.

However, not every person object might have an address property defined.

Instead of manually checking each step to avoid errors, optional chaining allows you to attempt to safely access the city with minimal code.

Here's how you do it: const city = person?.address?.city;.

This line of code elegantly checks if the person object exists, then if the address property exists, and finally tries to get the city value. If at any point something is missing, it gracefully returns undefined without throwing an error.

As always, I think it's easiest to understand these features when you see them in action.

Here's how you can apply optional chaining in a few different scenarios:

Accessing Object Properties

const book = {
  title: "You Don't Know JavaScript",
  author: {
    name: "Kyle Simpson",
    contact: {
      email: "kyle@example.com"
    }
  }
};

// Without optional chaining, it might look like this:
let email;
if (book && book.author && book.author.contact) {
  email = book.author.contact.email;
}

// With optional chaining
email = book?.author?.contact?.email;
console.log(email); // Outputs: kyle@example.com

Calling Methods Safely

const myObject = {
  myMethod: () => console.log("Method was called"),
};

// Without optional chaining, you might use something like the following:
myObject && myObject.myMethod();

// With optional chaining
myObject.myMethod?.(); // Outputs: Method was called


myObject.doesNotExist?.(); // Outputs undefined instead of an error  👀

Accessing Array Elements

const myArray = [10, 20, 30];

// Accessing an element safely
const secondItem = myArray?.[1];
console.log(secondItem); // Outputs: 20

// Trying to access an out-of-bounds index or on undefined
const fifthItem = myArray?.[4];
console.log(fifthItem); // Outputs: undefined

Whether you're accessing properties, calling methods, or dealing with arrays, optional chaining has your back, ensuring your code runs smoothly without tripping over missing data.

It's one feature in JS that I never knew how much I needed until I used it.

Happy coding! 👀

JSJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.