Understanding Optional Chaining in JavaScript: ?.

Sahil SudanSahil Sudan
3 min read

In React applications, you often work with deeply nested objects, such as API responses, state, or props. Accessing properties in these objects can sometimes result in runtime errors if the intermediate properties are null or undefined.

This is where optional chaining (?.) becomes a lifesaver, ensuring that your application doesn't crash by safely accessing properties.


What is Optional Chaining (?.)?

Optional chaining is a feature in JavaScript that allows you to safely access nested object properties, even if some properties in the chain don’t exist. It short-circuits and returns undefined when a property is null or undefined, instead of throwing an error.


Syntax Comparison

SyntaxUsage ScenarioOutcome
variablesValues?.data?.variablesUse this when any part of the object (variablesValues, data, variables) might not exist.Returns undefined if any property in the chain is null or undefined. No runtime error.
variablesValues.data.variablesUse this when you're certain all properties (variablesValues, data, variables) exist and are valid.Directly accesses the value. Throws an error if any part of the chain is null or undefined.

Comparison:

ScenariovariablesValues?.data?.variablesvariablesValues.data.variables
Data might be missing❌ Throws an error
Confident that all data exists✅ (but slower)✅ (faster)
Avoid errors on potentially null values

Real-Life Example in React

Scenario 1: Using ?. to Handle Uncertain Data

When working with an API response, it's common to encounter scenarios where some properties might be missing.

javascriptCopy codeconst variablesValues = {
  data: {
    variables: "Some value"
  }
};

const value = variablesValues?.data?.variables;
console.log(value); // Output: "Some value"

// If `variablesValues.data` or `variablesValues` were `undefined`, this would return `undefined`.

Scenario 2: Using . for Certain Data Structures

If you have full control over the data structure and are confident that all properties exist, you can directly access the value.

javascriptCopy codeconst variablesValues = {
  data: {
    variables: "Some value"
  }
};

const value = variablesValues.data.variables;
console.log(value); // Output: "Some value"

// Throws an error if `variablesValues` or `data` is `undefined`.

Performance Considerations

Using ?. introduces a slight overhead because it performs additional checks for null or undefined. However, this overhead is negligible compared to the safety and convenience it provides when dealing with unpredictable data.


Key Takeaways

  1. Use ?. when you're unsure about the existence of properties in an object chain (e.g., working with dynamic data).

  2. Use . when you're confident all properties in the chain exist and the object structure is reliable.

  3. Always prioritize safety in uncertain scenarios to avoid runtime errors, especially in production React applications.


By mastering optional chaining, you can write safer, cleaner, and more robust React applications, particularly when dealing with APIs and dynamic data structures.

0
Subscribe to my newsletter

Read articles from Sahil Sudan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sahil Sudan
Sahil Sudan