Angular Nullish Coalescing Operator (??)

By Arvind Rai, August 09, 2021
On this page we will learn using nullish coalescing operator (??) in Angular applications. Nullish values are either null or undefined. To handle nullish values, we use nullish coalescing operator (??) in JavaScript and TypeScript etc.
Since Angular v12, nullish coalescing operator (??) can be used in Angular HTML templates. It helps to write cleaner code in Angular HTML templates as well as in TypeScript.
Find the code snippet to use nullish coalescing operator (??) in HTML template.
{{ userName ?? getUserName() }} 
The above code is equivalent to below code.
{{ userName !== null && userName !== undefined ? userName : getUserName() }} 
On this page we will understand using nullish coalescing operator (??) in detail.

1. Technologies Used

Find the technologies being used in our example.
1. Angular 12.1.0
2. Node.js 12.14.1
3. NPM 7.20.3

2. Nullish Coalescing Operator (??)

The nullish coalescing operator (??) is a logical operator that has following syntax.
leftExpr ?? rightExpr 
If left-hand side operand is null or undefined, then right-hand side operand is returned otherwise left-hand side operand is returned. The nullish coalescing operator (??) has the fifth-lowest operator precedence, directly lower than || and directly higher than the conditional (ternary) operator.
Let us understand using nullish coalescing operator (??) in TypeScript by example.
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  ngOnInit() {
    const valA = null;
    const valB = undefined;
    const valC = "";
    const valD = "Varanasi";

    const outputA = valA ?? "Noida";
    const outputB = valB ?? "Delhi";
    const outputC = valC ?? "Prayagraj";
    const outputD = valD ?? "Aizawl";
    
    console.log(outputA); // Noida
    console.log(outputB); // Delhi
    console.log(outputC); // "" (empty string)
    console.log(outputD); // Varanasi
  }
} 

3. Short-circuiting

The nullish coalescing operator (??) is short-circuiting operator same as && and || operator. Short-circuiting operator means it does not evaluate the right-hand side if it is not necessary. Find the example.
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  ngOnInit() {
    //Example-1
    const outputA = this.fun1() ?? this.fun3(); 
    console.log(outputA);
    //Example-2
    const outputB = this.fun2() ?? this.fun3(); 
    console.log(outputB);    
  }
  fun1() {
    console.log('fun1 was called'); 
    return undefined;
  }
  fun2() {
    console.log('fun2 was called'); 
    return "Welcome";
  }
  fun3() { 
    console.log('fun3 was called'); 
    return "hello";
  }  
} 
Output for outputA is as below.
fun1 was called
fun3 was called
hello 
If the value of left-hand side function of ?? operator is null or undefined then right-hand side function is also executed otherwise only left-hand side function is executed. In the above code, example-1 will execute both functions and example-2 will execute only left-hand side function.
Output for outputB is as below.
fun2 was called
Welcome 

4. (??) with AND (&&) and OR (||) Operators

The AND (&&) and OR (||) operators cannot be used with (??) operator directly but we can use it with parenthesis ().
1.
const outputD = valA && valD ?? "Aizawl"; //SyntaxError 
2.
const outputD = valA || valD ?? "Aizawl"; //SyntaxError 
3.
const outputD = (valA && valD) ?? "Aizawl"; //Success 
4.
const outputD = (valA || valD) ?? "Aizawl"; //Success 

5. (??) with (?.) Operators

The optional chaining operator (?.) enables us to read value without error from reference variable that may be nullish (null or undefined). We can use optional chaining operator (?.) with nullish coalescing operator (??). Find the example.
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  ngOnInit() {
    let user = JSON.parse('{ "firstName": "Mohan" }');

    console.log(user.firstName?.toUpperCase() ?? "NA"); // MOHAN
    console.log(user.lastName?.toUpperCase() ?? "NA"); // NA
  }
} 

6. Nullish Coalescing Operator (??) in HTML Template

Nullish Coalescing Operator (??) can be used in HTML template since Angular v12. Find the example to use (??) in HTML template.
app.component.html
<p> {{valA ?? "Noida"}} </p>
<p> {{valB ?? "Delhi"}} </p>
<p> {{valC ?? "Prayagraj"}} </p>
<p> {{valD ?? "Aizawl"}} </p>

<p>{{(valA && valD) ?? "Aizawl"}}</p>
<p>{{(valA || valD) ?? "Aizawl"}}</p>

<p>{{user.firstName?.toUpperCase() ?? "No Data"}}</p>
<p>{{user.lastName?.toUpperCase() ?? "No Data"}}</p> 
app.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  valA = null;
  valB = undefined;
  valC = "";
  valD = "Varanasi";
  user = JSON.parse('{ "firstName": "Mohan" }');
  ngOnInit() {
    const outputA = this.valA ?? "Noida";
    const outputB = this.valB ?? "Delhi";
    const outputC = this.valC ?? "Prayagraj";
    const outputD = this.valD ?? "Aizawl";
    console.log(outputA); // Noida
    console.log(outputB); // Delhi
    console.log(outputC); // "" (empty string)
    console.log(outputD); // Varanasi
    
    console.log((this.valA && this.valD) ?? "Aizawl"); // Aizawl
    console.log((this.valA || this.valD) ?? "Aizawl"); // Varanasi

    console.log(this.user.firstName?.toUpperCase() ?? "NA"); // MOHAN
    console.log(this.user.lastName?.toUpperCase() ?? "NA"); // NA    
  }
} 
Find the print screen of the output.
Angular Nullish Coalescing Operator (??)

Run Application

To run the application, find the steps.
1. Download source code using download link given below on this page.
2. Use downloaded src in your Angular CLI application. To install Angular CLI, find the link.
3. Run ng serve using command prompt.
4. Access the URL http://localhost:4200

8. References

Angular v12 New Features
Nullish coalescing operator (??)

9. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us