JavaScript Nullish coalescing operator ‘??’

The nullish coalescing operator ?? provides a short syntax for selecting a first “defined” variable from the list. Check the post for more on JavaScript Nullish coalescing operator ‘??’

Simple example

Let’s assume that the result of 
valueA ?? valueB is:

  • valueA if it’s not null or undefined,
  • valueB, otherwise.

So, result = valueA ?? valueB is a short equivalent to:

result = (valueA !== null && valueA !== undefined) ? valueA : valueB;

Longer example

let firstName = null;
let lastName = undefined;
let nickName = "panayiotisgeorgiou";
alert(firstName ?? lastName ?? nickName ?? "Anonymous"); 

//show the first not-null/undefined variable 
Result panayiotisgeorgiou

Important Points:

  • The ?? operator is used to check null values and you can also assign a default value to a variable whose value is null(or nullable type).
  • You are not allowed to overload ?? operator.
  • It is right-associative.
  • In ?? operator, you can use throw expression as a right-hand operand of ?? operator which makes your code more concise.

Browser Support

At the time of this writing, it looks like the latest versions of Chrome, Firefox, Edge, and Safari are good with the nullish coalescing operator.

https://caniuse.com/#search=nullish

Follow me on Instagram

That’s it for now. 😉

If you liked this article, then please subscribe to my YouTube Channel for video tutorials.

You can also find me on Twitter and Facebook.