🍐Nullish coalescing operator

The nullish coalescing operator (??) is a new operator introduced in ECMAScript 2020 (ES2020) that allows you to provide a default value for an expression if it is null or undefined. It is similar to the logical OR operator (||), but it only returns the default value if the expression is null or undefined, rather than any falsy value.

Here is an example of how to use the nullish coalescing operator:

let x = null;
let y = undefined;
let z = 0;

console.log(x ?? 'default'); // 'default'
console.log(y ?? 'default'); // 'default'
console.log(z ?? 'default'); // 0

In this example, the nullish coalescing operator is used to provide default values for the variables x and y, which are null and undefined, respectively. The operator returns the default value of 'default' for these variables, but it returns the value of z (0) as is, because 0 is not null or undefined.

The nullish coalescing operator can be useful in situations where you want to provide a default value for an expression, but you do not want to use a falsy value (such as 0, '', or false) as the default. It can also be useful for distinguishing between null and undefined, which can be useful in certain cases.

For example, suppose you have a function that returns a user's name, or null if the user is not logged in. You could use the nullish coalescing operator to provide a default value for the user's name, like this

function getUserName(user) {
  return user?.name ?? 'Guest';
}

console.log(getUserName({ name: 'Alice' })); // 'Alice'
console.log(getUserName(null)); // 'Guest'
console.log(getUserName({})); // 'Guest'

In this example, the nullish coalescing operator is used to provide a default value of 'Guest' if the user object is null or undefined, or if the user.name property is null or undefined. If the user.name property is set to a non-nullish value, the operator returns that value instead.

Last updated