What Is the Optional Chaining Operator in JavaScript?

Introduced in ES11, the optional chaining operator (?.) allows you to access values within a chain of connected objects where a reference or function in the chain could potentially be a nullish value (i.e. undefined or null). It has the following syntax:

obj.value?.prop
obj.value?.[expr]
obj.array?.[index]
obj.method?.(args)

You can use optional chaining when:

For example:

// ES11+
const name = posts?.[0]?.author?.name;
const result = callback?.();
// ...

The expression is evaluated left-to-right, and when/if the left operand evaluates to a nullish value, then the execution of the entire chain is stopped and evaluated to undefined (i.e. it short-circuit evaluates to undefined).

Without optional chaining you would have to check if each reference or function in the chain is a nullish value (which in some cases could mean a lot of nested checks and repetition). For example, one way to do that is using the logical AND operator (&&) like so:

const name = posts.length
    && posts[0]
    && posts[0].author
    && posts[0].author.name
;
const result = callback && callback();
// ...

Here, the logical AND operator would return the first falsy value, or the last operand if there's no falsy value.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.