Null coalescing operator angular 2

AngularTypescriptNull Coalescing-Operator

Angular Problem Overview


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";

Angular Solutions


Solution 1 - Angular

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.

Solution 2 - Angular

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.

Solution 3 - Angular

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 

Solution 4 - Angular

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2526236View Question on Stackoverflow
Solution 1 - AngularRoman CView Answer on Stackoverflow
Solution 2 - AngularberslingView Answer on Stackoverflow
Solution 3 - AngularFlavio FranciscoView Answer on Stackoverflow
Solution 4 - AngularalexkovelskyView Answer on Stackoverflow