Optional Chaining Operator

Introduction

The Optional Chaining Operator (?.) is a modern JavaScript feature introduced in ECMAScript 2020 (ES11). It allows you to safely access nested object properties, array elements, and methods without causing an error if a property does not exist.

Without optional chaining, trying to access a property of undefined or null results in a runtime error. The optional chaining operator prevents this by returning undefined instead of throwing an exception.

For automation engineers, the optional chaining operator is extremely useful when working with API responses, JSON data, configuration files, environment variables, and optional object properties.


What is the Optional Chaining Operator?

The Optional Chaining Operator (?.) safely accesses a property or method of an object.

If the object is null or undefined, JavaScript returns undefined instead of throwing an error.

Syntax

object?.property

For nested properties:

object?.property?.subProperty

Why Do We Need the Optional Chaining Operator?

The optional chaining operator helps us:

  • Prevent runtime errors.

  • Safely access nested objects.

  • Simplify complex null checks.

  • Work with optional API fields.

  • Write cleaner and more readable code.


Problem Without Optional Chaining

Consider the following object:

const user = {
    name: "John"
};

console.log(user.address.city);

Output

TypeError: Cannot read properties of undefined

Since address does not exist, JavaScript throws an error.


Solution Using Optional Chaining

const user = {
    name: "John"
};

console.log(user.address?.city);

Output

undefined

Instead of throwing an error, JavaScript safely returns undefined.


Accessing Nested Properties

const employee = {
    name: "David",
    company: {
        department: {
            name: "QA"
        }
    }
};

console.log(employee.company?.department?.name);

Output

QA

If a property is missing:

console.log(employee.company?.location?.city);

Output

undefined

Using Optional Chaining with Arrays

Optional chaining can safely access array elements.

const fruits = ["Apple", "Banana", "Orange"];

console.log(fruits?.[1]);

Output

Banana

If the array does not exist:

let colors;

console.log(colors?.[0]);

Output

undefined

Using Optional Chaining with Methods

Optional chaining can safely call methods.

const person = {
    greet() {
        return "Hello";
    }
};

console.log(person.greet?.());

Output

Hello

If the method does not exist:

const person = {};

console.log(person.greet?.());

Output

undefined

Combining Optional Chaining with Nullish Coalescing

The optional chaining operator is often combined with the Nullish Coalescing Operator (??).

const user = {};

const city = user.address?.city ?? "Unknown";

console.log(city);

Output

Unknown

If city is missing, the default value "Unknown" is returned.


Real-World Example

Suppose a user profile contains optional address information.

const profile = {
    name: "Alice"
};

const city = profile.address?.city ?? "Not Available";

console.log(city);

Output

Not Available

Another example:

const order = {
    id: 101,
    customer: {
        name: "Rahul"
    }
};

console.log(order.customer?.name);

Output

Rahul

Automation Testing Example

Automation engineers frequently work with API responses where some fields may not always be available.

const response = {
    data: {
        user: {
            username: "admin"
        }
    }
};

console.log(response.data?.user?.username);

Output

admin

If the API does not return the user object:

const response = {
    data: {}
};

console.log(response.data?.user?.username);

Output

undefined

The script continues running without throwing an exception.


Example with default value:

const apiResponse = {};

const status =
    apiResponse.result?.status ?? "Status Not Available";

console.log(status);

Output

Status Not Available

Before and After Optional Chaining

Traditional Approach

if (
    user &&
    user.address &&
    user.address.city
) {

    console.log(user.address.city);

}

Modern Approach

console.log(user.address?.city);

The second approach is shorter, cleaner, and easier to maintain.


Common Mistakes

Forgetting ?.

Incorrect:

console.log(user.address.city);

If address does not exist, JavaScript throws a TypeError.

Correct:

console.log(user.address?.city);

Assuming ?. Returns Default Values

Incorrect assumption:

console.log(user.address?.city);

The operator returns undefined, not a custom default value.

Use ?? if a default value is required:

console.log(user.address?.city ?? "Unknown");

Using Optional Chaining on Variables That Don’t Exist

Incorrect:

console.log(profile?.name);

If profile has never been declared, JavaScript throws a ReferenceError.

Optional chaining only works on variables that exist but may contain null or undefined.


Best Practices

Use Optional Chaining for Nested Objects

Whenever object properties may be missing, use ?. to avoid runtime errors.


Combine with Nullish Coalescing

Use ?? to provide meaningful default values.

Example:

const email =
    user.profile?.email ?? "No Email";

Avoid Unnecessary Optional Chaining

If you know an object always exists, normal property access is sufficient.


Improve Readability

Use optional chaining to replace long chains of null checks.


Conclusion

The Optional Chaining Operator (?.) is a powerful feature that makes JavaScript code safer and easier to read. It prevents runtime errors by safely accessing object properties, array elements, and methods that may not exist.

In automation testing, optional chaining is especially valuable when working with unpredictable API responses, JSON data, and optional configuration values. Combined with the Nullish Coalescing Operator (??), it provides a clean and reliable way to handle missing data.


Frequently Asked Questions (FAQs)

What is the Optional Chaining Operator?

The optional chaining operator (?.) safely accesses properties or methods of an object without throwing an error if the object is null or undefined.


What is the syntax of the optional chaining operator?

object?.property

For nested properties:

object?.property?.subProperty

What happens if a property does not exist?

The operator returns undefined instead of throwing a TypeError.


Can optional chaining be used with arrays and methods?

Yes.

Examples:

array?.[0]
object.method?.()

Why is the optional chaining operator useful in automation testing?

Automation engineers use it to safely access API response data, JSON objects, configuration values, and optional properties without causing runtime errors.


Key Takeaways

  • The optional chaining operator (?.) safely accesses object properties.

  • It returns undefined if a property does not exist.

  • It prevents TypeError exceptions caused by missing properties.

  • It works with objects, arrays, and methods.

  • It simplifies long chains of null checks.

  • It is commonly combined with the nullish coalescing operator (??).

  • It is especially useful when working with API responses and JSON data.

  • It improves code readability and maintainability.

  • It should be used when object properties may be optional.

  • Understanding optional chaining helps write safer and more reliable JavaScript code.