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";
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 .
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.
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.
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.
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.
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.
Since Angular 12 you can also use ??
in the template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With