A blog for technology, SEO tips, website development and open source programming.

JavaScript Nullish coalescing operator ‘??’

0 1,435

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.

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.

Leave a Reply

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More