Optional Chaining Recap

Optional chaining (?.) is a powerful JavaScript feature that safely accesses nested object properties or calls methods without causing runtime errors if a reference is null or undefined.

Illustration of optional_chaining_recap
Illustration of optional_chaining_recap

💡 What Optional Chaining Does

It short-circuits property access or function calls when the value before ?. is null or undefined, returning undefined instead of throwing an error.

Key Use Cases

  • Accessing deeply nested properties safely
  • Calling methods only if they exist
  • Accessing array elements without errors
Comparison: Without vs With Optional Chaining
Without Optional ChainingWith Optional Chaining
user && user.address && user.address.street user?.address?.street
if (obj && obj.method) obj.method(); obj?.method?.();
arr && arr[0] arr?.[0]

⚠️ Important Details

Optional chaining only checks for null or undefined. If a property exists but is falsy (like false or 0), it will return that value.

How Optional Chaining Works

  • obj?.prop returns undefined if obj is null or undefined, else returns obj.prop.
  • obj?.[expr] safely accesses dynamic properties.
  • func?.() calls func only if it’s defined.

📌 Deep Dive: Simple Optional Chaining

JAVASCRIPT
const user = { name: "Anna", address: { city: "NY" } };

// Accessing city safely
console.log(user?.address?.city);  // "NY"

// Accessing a missing property safely
console.log(user?.contact?.email); // undefined, no error

// Calling a method safely
const person = {
  greet() { return "Hello"; }
};
console.log(person.greet?.());     // "Hello"
console.log(person.farewell?.());  // undefined, no error
Output
"NY"
undefined
"Hello"
undefined

💡 Why Use Optional Chaining?

It reduces the need for repetitive if checks and makes code cleaner and more readable, especially when working with complex or uncertain data structures.

Limitations

  • Does not protect against non-object types (e.g., accessing properties on numbers).
  • Cannot be used to assign values (e.g., obj?.prop = value will throw an error).

⚠️ Optional Chaining and Assignment

You cannot use optional chaining on the left side of an assignment. To safely assign a nested property, check existence first.