Nullish Coalescing Operator

Nullish Coalescing Operator ??

The Nullish Coalescing Operator (??) of JavaScript is a logical operator that enables us to set a default/fallback value when the value on it’s left are null or undefined. I was excited when I got to know this operator because of two main reasons,

  1. It makes the code clean and self-explanatory
  2. Prevents unforeseen logical bugs 🐞

How it works?

// Handling undefined
const data={};
const username = data.name ?? 'default name';
console.log(username); // default name

// Handling null
let a = null;
let b = a ?? 2021;
console.log(b); // 2021

Usage

As we can see in the code above, when the value on the left is null or undefined, the value on the right is returned. We do perform a lot of null checks in JavaScript, and those cases can be handled by using the Nullish coalescing operator and assigning a predefined default/fallback value.

Stop using OR (||) for null check

Yes, here’s the bug I was talking about. Before I knew about the Nullish coalescing operator (??) as usual I was using the logical OR operator (||) that returns the value on the right side when the value on the left contains null or undefined. Both the operators sound the same, so what’s the problem here? Well…

const score = null || 99;
console.log(score); // 99

const playerName = undefined || 'no name'; 
console.log(playerName); // no name

This above code is completely normal, but the logical operator also rules out 0, false and "" (empty strings) as falsy values and returns the value on the right.

const score = 0;

// Using || 
const totalScore = score || 'error';
console.log(totalScore); // error

// Using ??
const finalScore = score ?? 'error';
console.log(finalScore); // 0

Yes, using logical OR operator for null check can be dangerous as it returns the default value when compared to 0, false or an empty string.

Clean code

We use logical OR (||) not only for null check but normally as a logical operator itself but, when we use the Nullish coalescing operator (??) it’s clear that we’re handling null and undefined values thereby improving the code readability and overall developer experience.

Ready to squash some bugs 🐞 ?

📝Note: This feature is part of ES2020, older browsers may not support this and may require polyfills.