12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
15 : 05 : 56 : 49
Join egghead, unlock knowledge.

Want more egghead? It's 58% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 40% Off
Become a member
to unlock all features

    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.