Optional Chaining and Nullish Coalescing

Optional Chaining is one of the most highly-demanded ECMAScript features. This one was filed over 5 years ago.

If you are an angular developer, you might have used the elvis (?) operator on the component template. which provides similar functionality on the template.

So what is optional chaining and why developers were eagerly waiting for this feature ?

Optional chaining lets us write code where we can immediately stop running some expressions if we run into a null or undefined.

You can implement it by using the new ?. operator

Let’s imagine we have an book where the author and the authors  genres might not be present in the data. 

type Book = {
  title: string,
  author?: {    
    name: string,
    description?: string,
    genres?: string[]
  } 
};​

Now suppose you declare it with object book

declare const book: Book;

You can access the name of the author as below, Here currently we need to add an extra check to verify that book.author is not null or undefined

// Current Implementation : Without optional-chaining
let author = book && book.author && book.author.name;

With optional chaining, you simplify this statement as below, You just need to add ?. operator. 

// Optional-Chaining
let author = book?.author?.name;

TypeScript 3.7 has three different optional chaining variations. 

Optional Property Access

Property access is via the . operator​. During property access, you can add optional chaining as we have seen in the above example, this is called optional property access

Another example is :

// With Optional Property Access
let x = foo?.bar.baz();

// Without Optional Property access
let x = (foo === null || foo === undefined) ?       
undefined : foo.bar.baz();​

Optional Element Access

Optional chaining also works with the [] operators when accessing elements.

const authorName= book?.["author"]?.["name"];
const genres = book?.author?.genres?.[0];

Optional Call

When dealing with functions which may or may not exist at runtime, optional chaining supports only calling a function if it exists. This can replace code where you would traditionally write something like:

if (func) func() With optional chaining, you can simply write it as func?.();

For example, here is an optional call to the callback from an API request:

const callUpdateMetadata = (metadata: any) => Promise.resolve(metadata); // Fake API call

const updateAlbumMetadata = async (metadata: any, callback?: () => void) => {
   await callUpdateMetadata(metadata);
   callback?.();
};

?. acts differently than the && since && will act differently on “falsy” values (e.g. an empty string, 0, NaN, and, well, false).

Optional chaining will only take null or undefined as a signal to stop and return an undefined.

Nullish Coalescing is another useful feature released in TypeScript 3.7

The nullish coalescing operator is an alternative to || which returns the right-side expression if the left-side is null or undefined. The issue with || with is, it considers empty string and 0 as a false. which is not true in all scenarios, for example, if volume is null or undefined use 0.5 as default volume.
let x = volume || 0.5;
But the issue with || operator is if volume is 0, x will become 0.5 which is not intended.
?? avoids some unintended behavior from 0, NaN and "" being treated as falsy values.​
With nullish coalescing operator ?? you can fix the above issue.
let x = volume ?? 0.5;
?? operator returns right side value only when left size value is null or undefined.

In this article, we have seen the most awaited feature Optional Chaining & its variations and Nullish Coalescing.

I hope you like this article, please provide your valuable feedback and suggestions in below comment section🙂.

For more updates, Follow us 👍 on NgDevelop Facebook page.

If you use visual studio code editor then you might also like this article:Visual Studio Code tips and tricks