Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Optional chaining (?.)

Safe property access: returns undefined instead of an error if the object is missing.

Available since: ES2020

Syntax

obj?.prop / obj?.[key] / fn?.()

Examples

A nested property that may be missing:

const user = { name: 'Anna' };
 
console.log(user.address?.city);

Output:

undefined

Without ?. the same code throws:

const user = { name: 'Anna' };
 
try {
  console.log(user.address.city);
} catch (error) {
  console.log(error.name);
}

Output:

TypeError

Together with ?? and for calling a method:

const user = { name: 'Anna' };
 
console.log(user.address?.city ?? 'no city');
console.log(user.greet?.());

Output:

no city
undefined

Notes

The check works only for null and undefined. Do not put ?. everywhere: if an object must exist, an error is more honest than a silent undefined.

See also

  • Nullish coalescing (??) — Returns the right-hand value if the left is null or undefined.
  • TypeError — A wrong type error — for example, calling a method on undefined.
  • in — Checks whether an object has a property (inherited ones included).

Related recipes

In the tutorial

  • Optional chaining and ?? — Safe access to nested properties in JavaScript: the ?. operator, calling optional methods and defaults with ??.

Thanks for reading!

Donate to the site — we work hard for you.