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
Published 5 years ago
Updated 3 years ago

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.

Falk
Falk
~ 5 years ago

For correct I would have used val != null ? val : 0.5.

However, the new operator will make this even shorter and more readable, very nice!

Is this only a TS feature or will this go into the coming ES releases?

Rich Buggy
Rich Buggyinstructor
~ 5 years ago

There's a TC39 proposal to add it to ES.

Markdown supported.
Become a member to join the discussionEnroll Today