Become a member
to unlock all features

Level Up!

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


    Using the Null Coalescing operator with TypeScript 3.7

    Rich BuggyRich Buggy

    The videos shows you how to use the null coalescing operator (??) instead of logical or (||) to set default values in TypeScript 3.7 to prevent expected bugs in your 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




    Instructor: I'm going to start by assigning undefined to the variable vowel. I'm then going to assign the variable "correct" the value from the variable vowel, only if vowel is not undefined and not null. Otherwise, I'll use the default value 05. As developers, we like shorthand syntax. Commonly, we'll simply check vowel "or" and then a default value.

    I'm going to assign that to the variable "incorrect." Finally, I'll lock both of these to the console. When I run my code, you'll see both correct and incorrect are 05. If I assign vowel the number zero, then compile and execute my code again, you'll notice that the correct answer is zero and incorrect is 05. The reason incorrect is showing the default value instead of the value provided is that zero, NaN, and empty strings are all considered falsy.

    Starting with TypeScript 3.7, you can use the null coalescence operator as a shorthand syntax for explicitly checking if the value is null or undefined. Now when I compile or run my code, both correct and incorrect show zero.