Nullish Coalescing

A significant portion of modern JavaScript code is dedicated to handling uncertainty—specifically, dealing with variables that might be null or undefined.

The nullish coalescing operator (??) provides a highly concise way to establish default fallback values.

How It Works

The syntax is leftSide ?? rightSide.

  • If the value on the left is null or undefined, the value on the right is returned.
  • Otherwise, the value on the left is returned.
let myName = null;
console.log(myName ?? "Anonymous"); // Output: "Anonymous"

myName = "Lane";
console.log(myName ?? "Anonymous"); // Output: "Lane"

It is essentially a shorthand way of saying: “Use this variable, but if it is completely empty, use this default string instead.”

Practical Example

When querying databases or APIs, some fields might be left blank by users, resulting in null. The nullish coalescing operator allows you to assign a clean default value right at the point of usage.

const name = "James Holden";
const provider = "AT&T";
const phoneNumber = "555-123-4567";

// The user never selected a subscription type, so it was stored as null
const subscriptionData = null;

// Use ?? to default to "Guest" if the subscriptionData is null
const subscriptionType = subscriptionData ?? "Guest";

console.log(
  `Creating ${subscriptionType} Profile for ${name} with ${provider} at ${phoneNumber}.`
);