Understanding the Nullish Coalescing (??) Operator in JavaScript

Abstract image used to represent The Nullish Coalescing Operator (??) In JavaScript
Image by Jon Tyson.

In Brief

Use the nullish coalescing operator, ??, when a fallback should apply only to null or undefined. Unlike ||, it preserves valid falsy values such as 0, false and an empty string. Choose between the operators from the meaning of the data: absence and general falsiness are different conditions, even when they sometimes produce the same result.

I'll admit: I am possibly a little late to the game when it comes to the Nullish coalescing operator (??). I have only come across a realworld use in a code review earlier this week, which then resulted in a long and interesting conversation about the difference between ?? and the logical OR operator: ||.

So: in modern JavaScript development, the introduction of the nullish coalescing operator (??) brought with it a convenient way to handle default values in a concise and expressive manner. The operator provides a more precise and reliable alternative to the logical OR (||) operator in certain scenarios. In this article, I hope to explore the nullish coalescing operator, understand its behaviour, and compare it with the logical OR operator that we all know and love.


Understanding the Nullish Coalescing Operator

The nullish coalescing operator (??) is designed to evaluate and return the righthand side (RHS) expression only if the lefthand side (LHS) expression is nullish, which includes null and undefined. It allows us to provide a default value when dealing with potentially nullish values without relying on falsy values like empty strings, zero, or false.

Basic Usage

So, let's start with a fairly basic example to demonstrate the behaviour of the nullish coalescing operator:

const name = null;
console.log(name ?? 'Anonymous');  //=> 'Anonymous'

Here, the variable name is set to null. When we use the nullish coalescing operator, it checks if name is nullish and because it is explicitly set to null in this example returns RHS expression ('Anonymous').

Comparison with Logical OR Operator:

To better understand the differences between ?? and ||, let's compare the nullish coalescing operator with the logical OR operator in a more realworld type of scenario:

const foo = {
  name: '',
  age: 0,
};

// Using nullish coalescing operator
console.log(foo.name ?? 'Anonymous');  //=> ''
console.log(foo.age ?? 25);  //=> 0

// Using logical OR operator
console.log(foo.name || 'Anonymous');  //=> 'Anonymous'
console.log(foo.age || 25);  //=> 25

Here, we have an object foo with properties name and age. The nullish coalescing operator considers both an empty string ('') and zero (0) as nonnullish values, resulting in the default values being ignored and the LHS being returned.

When we use the logical OR operator instead, it evaluates foo.name and foo.age as falsy values, (both an empty string ('') and zero (0) are falsy, but not nullish). As a result, the RHS values 'Anonymous' and 25 are returned.


More Advanced Examples

As you might expect, the nullish coalescing operator can be combined with other JavaScript features, such as function calls and object properties. To delve into more advanced examples, let me share a couple of examples that illustrate its practical use.

Example 1: Function Parameter Defaults

const greetUser = name => {
  name = name ?? 'Anonymous';
  console.log(`Hello, ${name}!`);
};

greetUser();  //=> Hello, Anonymous!
greetUser('John');  //=> Hello, John!

In this example, the greetUser function takes a name parameter. By using the nullish coalescing operator, we can assign a default value of 'Anonymous' to name if it is null or undefined. In this way, we can ensure that the function can still execute correctly even if the name argument is omitted.

Example 2: Object Property Access

const user = {
  name: 'John',
  preferences: {
    theme: 'dark',
    language: null,
  },
};

const theme = user.preferences?.theme ?? 'light';
const language = user.preferences?.language ?? 'en';

console.log(theme);  //=> 'dark'
console.log(language);  //=> 'en'

Here, optional chaining (?.) stops the property access if user.preferences is null or undefined. The resulting value then reaches ??, which selects the fallback only when that value is nullish. The operators have separate jobs: ?. protects that step of the access, and ?? supplies the default. The example still assumes that user itself exists.


The Wrap‑up

To offer a bit of a conclusion: the nullish coalescing operator (??) provides a concise and accurate way to handle default values in JavaScript, particularly when dealing with potentially nullish values.

The big difference between ?? (the nullish coalescing operator) and || (the logical OR operator) is that ?? considers only nullish values (null and undefined), whilst treating other falsy values as valid. The logical OR operator considers all falsy values.

?? selects its fallback only for null or undefined, so values such as 0, false, and an empty string remain valid. || selects its fallback for every falsy value. Directly mixing ?? with || or && without parentheses is a syntax error; parentheses are required to define the grouping.


Want to find out more?

If you need senior handson support with a complex React or Next.js platform, migration, performance issue, or technical SEO problem, send me the context and I'll tell you where I can help.