Understanding Nullish Coalescing Feature of Angular 12
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:
- name= undefined;
- getName() {
- return this.name !== null && this.name !== undefined ? this.name : 'Name is undefined';
- }
Using Angular 12, it becomes:
- name= undefined;
- getName() {
- return this.name ?? 'Name is undefined';
- }
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.