# Javascript optional chaining operator (?.)

Have you ever found yourself having to write something like:

if ('user' in data && 'job' in data.user && data.user.job.name == 'Peter')
1

An endless if 'y' in z && z in x.y.z ...?

The Optional chaining (?.) (opens new window) operator is here to save you!

With the optional chaining operator you can simply do:

if (data?.user?.job?.name == 'Peter')
1

?. returns undefined if any of the properties (or functions in the case of function calls) don't exist.

It can be used together with the nullish coalescing operator (??) (opens new window) to return default values:

let name = data?.user?.job?.name ?? 'Default name';
1

Newsletter

If you'd like to subscribe to my blog, please enter your details below. You can unsubscribe at any time.

Powered by Buttondown.

Last Updated: 11/20/2023, 10:04:51 AM