1. 1
    Using the Null Coalescing operator with TypeScript 3.7
    1m 28s

Using the Null Coalescing operator with TypeScript 3.7

Rich Buggy
InstructorRich Buggy
Share this video with your friends

Social Share Links

Send Tweet

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.

Instructor: [00:00] 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.

[00:27] 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.

[01:09] 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.