{

Angular 12 nullish coalescing operator


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

This post covers what is nullish coalescing operator in javascript/typescript and how it is used in Angular 13 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 a parameter coalescing is of combining two values

Here is a syntax

firstvalue ?? second value

?? double question mark is a symbol for the null coalescing operator

If firstvalue is null or undefined, Returns the second value if secondvalue is null or undefined, returns the 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 was integrated into Angular 12 and released in 2021.

Angular 12 nullish coalescing operator

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

This is used in Angular typescript components as well as HTML templates.

Angular 12 double quotation operator in typescript component

Before Angular 12, We have to write the 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 the typescript component

Here is a usage of an 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, the Cleaner approach is

{{message ?? "default message" }}

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

  • number
  • string
  • boolean
  • object

Conclusion

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

It helps programmers to write 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.