What is the Nullish Coalescing Operator in JavaScript?

What is the Nullish Coalescing Operator in JavaScript?

Ferenc Almasi β€’ 2020 August 10 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

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:

Copied to clipboard!
// 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

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:

Copied to clipboard! Playground
// 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

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

Resource

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.