Angular 15 nullish coalescing operator

What is Nullish Coalescing Operator in javascript?

nullish coalescing operator is a logical operator introduced in the latest javascript i.e EcmaScript 2020. It also introduced in Angular 12 version onwards.

This post covers what is nullish coalescing operator in javascript/typescript and how it is used in Angular 15 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, Return 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 15 double quotation operator

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

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

Before Angular 12, We have to write the below code to check null or undefined in the Typescript 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() {
    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";
  }
}

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

When to use ?? (nullish coalescing) vs || (logical OR)?

both operators (??,||) are binary operators, that applies two operands.

Nullish Coalescing Operator(??): If the left operand is null or undefined, It gives right operand

Logical OR Operator(||): It return right operand if left operand has falsy values("",0,false,null,undefined,NaN)

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.