What Is the Optional Chaining Operator in JavaScript?

JavaScript optional chaining operator (?.)

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.function?.(args)

You can use optional chaining when:

  • Accessing object properties or calling object methods;
  • Accessing properties with an expression using the bracket notation of the property accessor;
  • Accessing array items;
  • Making function calls.

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.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.