82

What is the equivalent of null coalescing operator (??) in angular 2?

In C# we can perform this operation:

string str = name ?? FirstName ?? "First Name is null";
rsenna
  • 11,775
  • 1
  • 54
  • 60
user2526236
  • 1,538
  • 2
  • 15
  • 29

4 Answers4

127

Coalescing is performed via || operator, i.e.

let str:string = name || FirstName || "name is null and FirstName is null";

You can also read this question for more details and explanations.

Roman C
  • 49,761
  • 33
  • 66
  • 176
  • 27
    Or operator(||) is not same exactly with nullish coalescing. For example: "" || "ibrahim" return "ibrahim" and 0 || "ibrahim" return "ibrahim" again. But with coalescing first operation returns "" and second returns 0. Because nullish coalescing only control whether the left-sided value is equal null or undefined – İbrahim Dolapci Jul 16 '18 at 15:44
  • 5
    Beware - this is not null coalescing operator as `false || true` returns `true`. – Vedran Apr 18 '19 at 16:33
  • 1
    For anyone who thinks this wouldn't matter since the `name` and `FirstName` variables are most likely `strings`, consider how JavaScript and TypeScript handle empty strings. If the `name` and `FirstName` fields are empty strings it would result in `name is null and First Name is null` despite neither of them being null. – Michael Ziluck Mar 27 '20 at 20:58
6

In Typescript

Typescript introduced null coalescing with version 3.7, so if you're running on 3.7 or higher you can simply write:

const str = name ?? firstName ?? "Name and First Name are both null";
const x = foo?.bar.baz() ?? bizz();

See https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing.

In the Angular Template

Since Angular 12 you can also use ?? in the template.

bersling
  • 17,851
  • 9
  • 60
  • 74
1

Maybe what you want achieve is this:

let str =
    typeof (name) !== 'undefined' && name !== null ?
        name : typeof (FirstName ) === 'undefined' || FirstName  === null ?
        "First Name is null" : FirstName 
Flavio Francisco
  • 755
  • 1
  • 8
  • 21
  • 1
    If the `name` and `FirstName` fields are empty strings it would result in `First Name is null` despite neither of them being null. – Michael Ziluck Mar 27 '20 at 20:57
0

The operator was added in TypeScript 3.7 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing

alexkovelsky
  • 3,880
  • 1
  • 27
  • 21