What is Nullish coalescing - ??

avatar

Borislav Hadzhiev

Fri Feb 26 20212 min read

banner

Photo by Sam Hull

Theory and differences between || and ?? #

Nullish coalescing enables us to specify a fallback for when a value is null or undefined.

You have probably written code like:

let employeeSalaryFromDb; const salary = employeeSalaryFromDb || 1000;

We are just checking if the employeeSalaryFromDb value is truthy, if it is we short circuit and assign that value to the salary variable.

If employeeSalaryFromDb is falsy we assign the value to the right of the || operator to the salary variable.

In typescript you could do:

let employeeSalaryFromDb; const salary = employeeSalaryFromDb ?? 1000;

In this case we check if employeeSalaryFromDb is null or undefined - if so - we assign the value to the right of the ?? operator to the salary variable.

In any other case - we short circuit and we assign the value of employeeSalaryFromDb to the salary variable.

You can see how the || and ?? operators are slightly different.

In the case of || - if we have any falsy value to the left of the operator - then the value to the right of the operator is returned.

For ?? - if we have a null or undefined value to the left of the operator - the value to the right of the operator is returned. Which does not include falsy values like '', NaN, 0, etc.

  • || - if (falsy) {return value to the right of operator}
// a is false const a = '' || false;
  • || - if (truthy) {return truthy value}
// b is 'hello' const b = 'hello' || 'world';
  • ?? - if (null || undefined) {return value to the right of operator}
let c; // logs 'hello' console.log(c ?? 'hello'); const d = null; // logs 'hello' console.log(d ?? 'hello');
  • ?? - if (falsy && !(null || undefined)) {return falsy value}
const e = 0; // logs 0 console.log(e ?? 'hello');
  • ?? - if (truthy) {return truthy value}
// logs 'hi' console.log('hi' ?? 'world');

End #

The ?? operator is more specific than the || operator because it only evaluates what's to the right hand side if the left hand side value is null or undefined. Sometimes the || operator has unintended behavior for 0 or NaN values, which are falsy. So you could have something like:

const quantity = 0; // logs 'specify quantity' even tho we have already done that console.log(quantity || 'specify quantity');

The correct operator for the job is ??:

const quantity = 0; // logs 0 console.log(quantity ?? 'specify quantity');

As of the 26th of February 2021, the ?? operator is supported by about 85.68% of browsers - caniuse.com.

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee