Last modified: Jul 21, 2026

JavaScript Optional Chaining with Variables

JavaScript optional chaining is a modern feature that helps you access deeply nested object properties safely. It prevents errors when a property or variable might be null or undefined. This article explains how to use optional chaining with variables in your code.

What is Optional Chaining?

Optional chaining, written as ?., stops evaluation if the value before it is null or undefined. Instead of throwing an error, it returns undefined. This is very useful when working with data that may be incomplete.

Before optional chaining, developers wrote long checks like if (obj && obj.prop). Now you can use obj?.prop for cleaner code.

Using Optional Chaining with Variables

You can use optional chaining directly on variables. If a variable might be null or undefined, you can safely access its properties. This is common when dealing with API responses or user input.

Here is a simple example:

// Define a variable that might be null
let user = null;

// Access a property safely
let userName = user?.name;
console.log(userName); // Output: undefined
undefined

In this code, user?.name returns undefined because user is null. Without optional chaining, this would throw an error.

Chaining Multiple Levels

Optional chaining works for multiple levels of nesting. You can chain several ?. operators together. This is perfect for deep objects.

Consider this example:

// Deeply nested object
let data = {
  user: {
    profile: {
      name: "Alice"
    }
  }
};

// Access safely
let city = data?.user?.profile?.city;
console.log(city); // Output: undefined

// Access existing property
let name = data?.user?.profile?.name;
console.log(name); // Output: "Alice"
undefined
Alice

Notice how city returns undefined without error. The chain stops at the missing property.

Optional Chaining with Variables in Functions

You can also use optional chaining with function calls. If a method might not exist, ?. prevents a runtime error. This is useful for optional callbacks.

Here is an example:

// Define a variable with a method
let obj = {
  greet: function() {
    return "Hello!";
  }
};

// Call method safely
let greeting = obj?.greet?.();
console.log(greeting); // Output: "Hello!"

// If method is missing
let empty = {};
let result = empty?.greet?.();
console.log(result); // Output: undefined
Hello!
undefined

The ?. checks if greet exists before calling it. If not, it returns undefined.

Combining with Nullish Coalescing

Optional chaining works well with the nullish coalescing operator ??. This operator returns a default value when the left side is null or undefined. Together, they provide safe access and fallback values.

Example:

// Variable may be undefined
let config = {
  theme: null
};

// Use optional chaining and nullish coalescing
let theme = config?.theme ?? "light";
console.log(theme); // Output: "light"
light

Here, config?.theme returns null, and ?? provides the default "light".

Common Use Cases

Optional chaining is often used with variables from external sources. For example, when fetching data from an API, some fields may be missing. Using ?. makes your code robust.

Another use case is with JavaScript variables in HTML. If you access properties from DOM elements that might not exist, optional chaining prevents errors. Learn more about JavaScript Variables in HTML for safer DOM interactions.

You can also use it when iterating over arrays of objects. If an array element is null, optional chaining avoids crashes. For more on variable handling, see Types of JavaScript Variables.

Best Practices

Use optional chaining only when a value might be missing. Do not overuse it, as it can hide bugs. Always check if the variable is expected to be null or undefined.

Remember that optional chaining works with variables, not with assignments. You cannot use ?. on the left side of an assignment operator. For example, obj?.prop = value is invalid.

Browser Support

Optional chaining is supported in modern browsers and Node.js 14+. For older environments, you may need a transpiler like Babel. Always check your target audience.

If you are new to JavaScript variables, review the JavaScript Variable Declaration Guide to understand how variables work.

Conclusion

JavaScript optional chaining with variables is a powerful tool for writing safer code. It simplifies nested property access and prevents runtime errors. By combining it with nullish coalescing, you can provide default values easily. Practice using ?. in your projects to make your code cleaner and more reliable. Start today and avoid those frustrating "Cannot read property" errors.