Understanding Nullish Coalescing Feature of Angular 12

Updated on: May 26, 2021

Nullish Coalescing is a new feature released in Angular 12, Angular 12 got released on May 12th 2021. Nullish Coalescing helps to check for whether variable is null or undefined. If variable value is null or undefined, then Nullish Coalescing feature helps us to assign default value to a variable instead of keeping it Null or Undefined.

Following is the example of Nullish Coalescing in Angular, in this example we have declared a variable "name", to which we have assigned "undefined" value, and in the getName() method instead of checking for Null and Undefined separately we checked with the Nullish Coalescing Syntax ("??").

Before Angular 12, we had to write following Syntax to perform the check of Null and Undefined:

  1. name= undefined;
  2. getName() {
  3.    return this.name !== null && this.name !== undefined ? this.name : 'Name is undefined';
  4. }

Using Angular 12, it becomes:

  1. name= undefined;
  2. getName() {
  3.    return this.name ?? 'Name is undefined';
  4. }

This feature works with all the datatypes such as number, string, boolean etc. You can also use this feature for various purposes, such as to check the return result from Ajax call and perform necessary action, if result is null or undefined.