loading...

Optional chaining is what you've been waiting for

jfbrennan profile image Jordan Brennan Updated on ・1 min read

Do you prefer the brevity of truthy/falsey in JavaScript and often rely on it when writing conditionals like:

if (state.user.firstName) {
  alert(`Welcome ${state.user.firstName}`);
}

But you've probably learned the hard way that evaluating nested properties like that runs the risk of hitting an undefined object and getting the most familiar error ever:
Uncaught TypeError: Cannot read property 'firstName' of undefined

So you add a check:

if (state.user && state.user.firstName) {
  alert(`Welcome ${state.user.firstName}`);
}

Yeah, problem solved, but don't those extra truthy checks bug you? Me too.

With the new "optional chaining" operator in JavaScript, which is supported in all the latest browsers, you can now do what you've always wished you could do:

if (state.user?.firstName) {
  alert(`Welcome ${state.user.firstName}`);
}

The operator verifies the object - the one with the ?., i.e. user?. - is not null or undefined before accessing the property - firstName - and gracefully resolves to undefined if it is.

You can check really deep:

if (state.user?.info?.name?.first) {
  alert('You should rethink your data model!');
}

Conditionals are where I've wanted this the most, but it's also really handy when invoking functions that may not exist:

optionalCallback?.()

Checkout the full docs to see even more options for using this handy little operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Posted on by:

jfbrennan profile

Jordan Brennan

@jfbrennan

Building great products

Discussion

pic
Editor guide
 

Awesome tip. I learned this a while ago and forgot it existed ha! Thanks 🙏🏽