TypeScript Nullish Coalescing Operator: Always Have a Fallback Value

A fallback value without null and undefined with the Nullish Coalescing operator

Photo by Tianyi Ma on Unsplash

Nullish coalescing operator

Released in TypeScript 3.7 version, we have a new logical operator available. It’s called and looks like this . But what does it do? To use it you need to have two values, one on the left and one on the right. In the middle, we use the .

If the value on the left of the operator is or , then the right-handed value will be used for a fallback. So by using this, you prevent having or values in your code. Sounds great, let’s take a look at the example below:

const var01 = null;const example01 = var01 ?? 'My other value';console.log(example01); // 'My other value'

will result in . Because the left-handed value is , the right-handed value will be returned. The same situation applies with . See the below example.

const var02 = undefined;const example02 = var02 ?? 'My other value';console.log(example02); // 'My other value'

For all other scenario’s which don’t include or as a value, it returns the left-handed value.

const var03 = 'Hello';
const var04 = true;
const example03 = var03 ?? 'My other value';
const example04 = var04 ?? 'My other value';
console.log(example03); // 'Hello'
console.log(example04); // true

OR logical operator (comparing)

The new nullish coalescing operator is less strict than the OR operator. The number zero , not a number , or an empty string are allowed with . However, these values are falsy and not allowed with which causes undesired behavior is certain situations. and are not allowed in both operators.

const var05 = 0;
const var06 = NaN;
const var07 = '';
// Will return right-hand (restricts)
const example05 = var05 || 'My other value';
const example06 = var06 || 'My other value';
const example07 = var07 || 'My other value';
// Will return left-hand (allows)
const example08 = var05 ?? 'My other value';
const example09 = var06 ?? 'My other value';
const example10 = var07 ?? 'My other value';

Note: using and together will give a .


Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com

Thanks to JS dev Ray

Jeroen Ouwehand

Written by

🔥Writing new articles every month — Software Developer from The Netherlands — Angular-TypeScript-Flutter-Golang-Node.js — Twitter/Github: Jeroenouw

Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade