Use Optional Chaining to Safely Handle Objects with Unknown Properties

Yoni Weisbrod
InstructorYoni Weisbrod
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

Optional Chaining provides a safe way to handle situations where you don't know whether specific properties exist on a given object. Rather than resorting to long conditional logic or nested ternaries, optional chaining is a concise way to only access properties if they exist - and if they don't, to return undefined rather than throw an error.

Please note: This feature is still making its way through the TC39 proposal process. To use it in your project today, you can enable it using Babel's Optional Chaining plugin.

Instructor: [0:00] A good candidate for optional chaining would be to navigate down a nested object where we don't exactly know what the structure will be.

[0:08] Here, we know that we can get Kevin's favorite coffee flavor. But what if we want to get his favorite ice cream flavor, and we don't know if the server sends it? We try to access it normally and we end up with an error.

[0:20] Now, using optional chaining, we can add this question mark and period. Instead of ending up with an error, we'll get undefined. We can keep trying to navigate down the nested object as far we want and still not encounter an error.

[0:34] Optional chaining can also help when you want to call a function on an object, but you're not sure if the function is defined. Just be aware that there's a pitfall here.

[0:43] If a property is already defined with that name, but it's not a function, you will still get an error rather than undefined.

egghead
egghead
~ 11 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today