1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Use Optional Chaining to Safely Handle Objects with Unknown Properties

    Yoni WeisbrodYoni Weisbrod
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    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.