Optional Chaining (JavaScript)

Optional chaining (?.) safely reads deeply nested properties. If a value in the chain is null or undefined, it returns undefined instead of throwing an error.

JavaScript

Without optional chaining, accessing a.b.c when b is missing throws a TypeError. With ?., the expression short-circuits and gives undefined.

It works for properties, array indexes, and function calls (obj?.method?.()).

Syntax

object?.property

Examples

JavaScript

const user = { profile: null };
console.log(user.profile?.name);

Output:

undefined

See also

Back to the Dictionary