DEV Community

Shameer Chagani
Shameer Chagani

Posted on

1 1

What is Optional Chaining (?.) In javaScript?

Optional chaining is a feature that simplifies accessing nested properties or calling functions on objects that may be nullish or undefined. It allows you to avoid the common "TypeError: Cannot read property 'x' of undefined" error when accessing properties deep within an object hierarchy.

Here's an example to illustrate how optional chaining works:

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

// Accessing nested property without optional chaining
const city = user.address.city; // 'New York'

// Accessing nested property with optional chaining
const city = user.address?.city; // 'New York'

// Accessing non-existent property with optional chaining
const country = user.address?.country; // undefined
Enter fullscreen mode Exit fullscreen mode

In the example above, the address property is optional. With optional chaining (?.), you can safely access the city property of address even if address itself is null or undefined. If address is null or undefined, the expression will simply return undefined.

Optional chaining is especially useful when working with data from APIs or when dealing with complex object structures where certain properties may not always exist.

Note that optional chaining is supported in modern JavaScript environments, including most up-to-date browsers. However, if you're working in an older environment or need to support older browsers, you might need to transpile your code using a tool like Babel to ensure compatibility.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs