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 the Nullish Coalescing Operator to Set Object Defaults

    Yoni WeisbrodYoni Weisbrod
    javascriptJavaScript

    The nulliish coalescing operator (??) allows us to be more explicit when setting object defaults. It allows us to ensure that only values that are "nullish" (either null or undefined) cause the default value to be taken, rather than anything that evaluates to false.

    It's a safer way to operate.

    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 Nullish Coalescing 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: We want to write some logic that takes into account whether a user that arrived from the server is an active or an inactive user.

    In our logic, we've set up a default active status to be true. For this particular user, we're going to say that if the server sends an active status, take that, and if not, take the default active status. This leaves us with a logic issue, as we can see here.

    The user status is considered to be true, even though it's actually false. This is because the OR operator will continue evaluating the right operand in any case that the left one is false.

    To rectify this, we're going to swap the OR operator with a nullish coalescing operator, which will only continue to the right operand if the left one is null or undefined. In this case, it's false, so that will be the final value.

    This operator would be equally valuable if we were working with any falsy value that was not null or undefined. For instance, if we had a number that was set to zero, or if we had a property that was just an empty string, we would encounter the same problem as a false.

    This operator will be commonly used with the optional chaining operator when we're trying to access a property from a deeply-nested object. We don't know necessarily what the value of the property will be, but we do know that if it's not present, it will be undefined.

    If we try to grab a property in the deeply-nested object, and it's a falsy value, the nullish coalescing operator will continue to do its job and make sure that only the left operand is evaluated.