Angular 12 nullish coalescing operator


nullish coalescing operator is logical operator introduced in latest javascript i.e EcmaScript 2020.

This post covers what is nullish coalescing operator in javascript/typescript and how it is used in Angular 12 components.

nullish coalescing operator is a logical operator used to check value is null or undefined on two values.

nullish abbreviated as null and undefined values of an parameter coalescing is of combining two values

Here is an syntax

firstvalue ?? second value

?? double question mark is an symbol for null coalescing operator

If firstvalue is null or undefined, Returns second value if secondvalue is null or undefined, returns first value

Here is an example

const output = null ?? '123';
console.log(output); // 123

const output1 = 11 ?? 0;
console.log(output1); //11

The same operator integrated in Angular 12 and released in 2021.

Angular 12 nullish coalescing operator

?? double quotation introduced as part of Angular 12 language.

This will be used in Angular typescript components as well as html template

Angular 12 double quotation operator in typescript component

Before Angular 12, We have to write below code to check null or undefined

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  message = undefined;
  getMessage() {
    if (this.message !== null && this.message !== undefined) {
      return "default message";
    }
    return this.message;
  }
}

With Angular 12, We can simplify the null and undefined check and write a clean code in typescript component

Here is an usage of operator in component

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  message = undefined;
  getMessage() {
       return this.message ?? 'Default message';

  }
}

Angular 12 double quotation operator in html template

In html template component, app.component.html

{{message !== null && message !== undefined ? message : "default message" }}

With Angular12, Cleaner approach is

{{message ?? "default message" }}

This nullish operator applies to all data type values of a typescript

  • number
  • string
  • boolean
  • object

Conclusion

This helps to write a clean and simple code in writing Angular components, Although It is bit difficult to learn initially.

It helps programmer to write a well written code

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.