Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null coalescing operator angular 2

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"; 
like image 562
user2526236 Avatar asked Apr 08 '17 18:04

user2526236


People also ask

What does 2 question marks mean in typescript?

means. The double question marks (??) are also called nullish coalescing operators and they allow to use of a default value set on the right side of the operator in case the initial value from the left side of the operator is null or undefined .

What is the use of null coalescing operator?

The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null ; otherwise, it evaluates the right-hand operand and returns its result.

What does double question mark mean in Angular?

Double question marks(??) or nullish coalescing operator helps us to assign default values to null or undefined variables in Angular and Typescript. It's often called as Null coalescing operator. It's introduced as part of Typescript 3.7 version.

What is two question marks react?

It's an operator that simply returns the right-side expression when the left side expression is either null or undefined . Unlike the OR operator, the nullish coalescing operator is a situational operator that allows you to return 0 and empty string "" as a valid value for your application.


2 Answers

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.

like image 65
Roman C Avatar answered Sep 17 '22 10:09

Roman C


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.

like image 21
bersling Avatar answered Sep 20 '22 10:09

bersling