What is the Nullish Coalescing Operator in JavaScript?

What is the Nullish Coalescing Operator in JavaScript?

Ferenc Almasi β€’ 2020 August 10 β€’ πŸ“– 2 min read

The nullish coalescing operator (??) in JavaScript works similar to the logical OR operator. With logical OR, you can use a short circuit evaluation to provide default values:

// Short circuit (set default values) with logical OR
const fileName = this.fileName || '😢';

// If this.fileName is undefined, 😢 will be used as a fallback value
logical-or.js
Copied to clipboard!

However, by using the nullish coalescing operator, you can return the left hand side of the operand if it's falsy, but not null or undefined:

// Use the nullish coalescing operator to filter out null and undefined values:

const foo = null ?? 'Foo Fighters';
console.log(foo); // This will return β€œFoo fighters”

const age = 0 ?? 42;
console.log(age); // This will return 0

// Unlike the logical OR operator, it will return the left 
// operand if it’s a falsy value which is not null or undefined
// eg.: β€œβ€ or 0
nullish-coalescing-operator.js
Copied to clipboard!

This is not the case for logical OR. It will return the right-hand side, if the value is falsy. (Which means 0 or "" are also included)

Keep in mind, this is only supported for the latest browsers. You can check the support table at caniuse.com

If you are using babel, you can use the @babel/plugin-proposal-nullish-coalescing-operator plugin for it.

What is the Nullish Coalescing Operator in JavaScript?
If you would like to see more Webtips, follow @flowforfrank
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Resource

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended