Nullish coalescing operator '??'

What is the Nullish coalescing operator '??' in JavaScript?

The Nullish coalescing operator '??' is a new addition to JavaScript introduced in ECMAScript 2020. It is used to provide a default value when the value on the left-hand side of the operator is null or undefined.

The '??' operator can be seen as a shorthand way of writing a conditional statement to check for null or undefined values and provide a default value in such cases.

Syntax

The syntax of the Nullish coalescing operator is as follows:

valueToCheck ?? defaultValue

valueToCheck ?? defaultValue
 
result = a ?? b;

The result of a ?? b is:

  • if a is defined, then a,
  • if a isn’t defined, then b.

We can rewrite result = a ?? b using the operators that we already know, like this:

result = (a !== null && a !== undefined) ? a : b;

It means that, the expression will evaluate if 'a' is null or undifined. If it is, then 'b' will be returned. Otherwise, 'a' will be returned.

Examples

Let's look at some examples to understand the usage of the Nullish coalescing operator:

// Example 1
const username = null;
const displayName = username ?? 'Guest';
console.log(displayName);  // Output: Guest
 
// Example 2
const age = 0;
const validAge = age ?? 18;
console.log(validAge);  // Output: 0
 
// Example 3
const address = undefined;
const defaultAddress = address ?? 'Unknown';
console.log(defaultAddress);  // Output: Unknown

In Example 1, the `username` variable is assigned the value `null`, so the Nullish coalescing operator returns the defaultValue 'Guest', and the `displayName` variable is assigned the value 'Guest'.

In Example 2, although the `age` variable is assigned the value `0`, which is a falsy value, the Nullish coalescing operator still considers it as a valid value and returns it.

In Example 3, the `address` variable is assigned the value `undefined`, so the Nullish coalescing operator returns the defaultValue 'Unknown', and the `defaultAddress` variable is assigned the value 'Unknown'.

Example 4:

We can also use a sequence of '??' to select the first value from a list that isn’t null/undefined.

Let’s say we have a user’s data in variables firstName, lastName or nickName. All of them may be not defined, if the user decided not to fill in the corresponding values.

We’d like to display the user name using one of these variables, or show “Anonymous” if all of them are null/undefined.

Let’s use the '??' operator for that:

let firstName = null;
let lastName = null;
let nickName = "Supercoder";
 
// shows the first defined value:
alert(firstName ?? lastName ?? nickName ?? "Anonymous"); // Output: Supercoder

Comparison with OR '||' operator

The OR '||' operator can be used in the same way as '??'.

For example, in the code above we could replace '??' with '||' and still get the same result:

let firstName = null;
let lastName = null;
let nickName = "Supercoder";
 
// shows the first truthy value:
alert(firstName || lastName || nickName || "Anonymous"); // Supercoder

Historically, the OR || operator was been there since the beginning of JavaScript, so developers were using it for such purposes for a long time.

On the other hand, the nullish coalescing operator ?? was added to JavaScript only recently, and the reason for that was that the people weren’t quite happy with ||.

The important difference between them is that:

  • '||' returns the first truthy value.
  • '??' returns the first defined value.

In other words, || doesn’t distinguish between false, 0, an empty string "" and null/undefined. They are all the same – falsy values. If any of these is the first argument of ||, then we’ll get the second argument as the result.

In practice though, we may want to use default value only when the variable is null/undefined. That is, when the value is really unknown/not set.

For example, consider this:

let height = 0;
 
alert(height || 100); // 100
alert(height ?? 100); // 0

  • The height || 100 checks height for being a falsy value, and it’s 0, falsy indeed.so the result of || is the second argument, 100.
  • The height ?? 100 checks height for being null/undefined, and it’s not,so the result is height “as is”, that is 0.

In practice, the zero height is often a valid value, that shouldn’t be replaced with the default. So ?? does just the right thing.

Precedence

The precedence of the ?? operator is the same as ||.

That means that, just like ||, the nullish coalescing operator ?? is evaluated before = and ?, but after most other operations, such as +, *.

So we may need to add parentheses in expressions like this:

let height = null;
let width = null;
 
// important: use parentheses
let area = (height ?? 100) * (width ?? 50);
 
alert(area); // 5000

Otherwise, if we omit parentheses, then as * has the higher precedence than ??, it would execute first, leading to incorrect results.

// without parentheses
let area = height ?? 100 * width ?? 50;
 
// ...works this way (not what we want):
let area = height ?? (100 * width) ?? 50;

Using '??' with '&&' or '||'

Due to safety reasons, JavaScript forbids using ?? together with && and || operators, unless the precedence is explicitly specified with parentheses.

The code below triggers a syntax error:

let x = 1 && 2 ?? 3; // Syntax error

The limitation is surely debatable, it was added to the language specification with the purpose to avoid programming mistakes, when people start to switch from || to ??.

Use explicit parentheses to work around it:

let x = (1 && 2) ?? 3; // Works
 
alert(x); // 2

Key Takeaways

Here are some key takeaways about the Nullish coalescing operator '??' in JavaScript:

  • The Nullish coalescing operator '??' is used to provide a default value for null or undefined values.

  • The syntax of the '??' operator is `valueToCheck ?? defaultValue`.

  • It returns the valueToCheck if it is not null or undefined, otherwise, it returns the defaultValue.

  • It differs from the logical OR operator '

  • The operator '??' has a very low precedence, only a bit higher than ? and =, so consider adding parentheses when using it in an expression.
  • It’s forbidden to use it with || or && without explicit parentheses.

With the Nullish coalescing operator, you can write more concise code when dealing with null or undefined values, making your code more readable and less error-prone.

Comments

Popular posts from this blog

Limitations of JavaScript

'for in' Loop

in Operator