DEV Community

Cover image for Nullish Coalescing support in Angular template
Avinash Dalvi for This is Angular

Posted on • Originally published at internetkatta.com

Nullish Coalescing support in Angular template

Hello Devs,

I am going to explain about Nullish Coalescing (??) . Few days back while reading release details about Angular 12 I just got to know about this new word and how to write cleaner code in typescript. So, now Angular 12 view template is supporting Nullish Coalescing(??)

Let's first understand the meaning of Nullish Coalescing (??). Then how it is supported in Angular 12 version view template.

What is Nullish Coalescing (??) ?

Nullish - means null or undefined

Coalescing - means combine (elements) in a mass or whole.

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

nullish-coalescing.png

const a = null ?? 'hello world';
console.log(a);
// output: "hello world"

const b = 0 ?? 2;
console.log(b);
// output: 0
Enter fullscreen mode Exit fullscreen mode

Syntax to use -

 

(Left side expression)   ?? ( Right side expression) 
Enter fullscreen mode Exit fullscreen mode

Note : The nullish coalescing operator avoids this pitfall by only returning the second operand when the first one evaluates to either null or undefined (but no other falsy values) (e.g., '' or 0).

Another point to mentioned is && or || operator cannot pair directly with ?? operator. You have to provide parenthesis to explicitly indicate precedence is correct.

Not allow 🚫

null || undefined ?? "Hello World"; // raises a SyntaxError
true || undefined ?? "Hello World"; // raises a SyntaxError
Enter fullscreen mode Exit fullscreen mode

Allow ✅

(null || undefined) ?? "Hello World "; 
// Output "Hello World"
Enter fullscreen mode Exit fullscreen mode

Now you understand what is Nullish Coalescing (??). Let's understand how this is supported in Angular 12.

Currently if you are using a statement in a template like this. Where imageUrl is either set by component or child component. if imageURL is not set then go for getRandomImages() as default variable.

{{imageURL !== null && imageURL !== undefined ? imageURL : defaultImageURL }}
Enter fullscreen mode Exit fullscreen mode

Can be written using Nullish Coalescing (??)

{{ this.imageURL ?? this.defaultImageURL }} 
Enter fullscreen mode Exit fullscreen mode


 Github Code Link

Thanks for reading this blog. Hope you understand this concept. And if you have any query related to this concept can reach out to me over my twitter handle  @aviboy2006 or can raise an issue on GitHub link. If you like this blog don't forgot drop star on GitHub repository.

References :

Top comments (0)