DEV Community

Cover image for Nullish Coalescing Operator
Aaron Goldsmith
Aaron Goldsmith

Posted on

Nullish Coalescing Operator

The nullish coalescing operator ?? is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

const nullValue = null;

const val1 = nullValue ?? "default";

console.log(val1); // "default"
Enter fullscreen mode Exit fullscreen mode

It is similar to the traditional 'or' logical operator ||, but the difference is that || will return the right-hand side operand with any falsy value, such as an empty string, 0 or NaN, not only null or undefined.

For example:

const val = null ?? 'default';
console.log(val);
// logs "default"

const val2 = 0 ?? 88;
console.log(val2);
// logs 0 because it is falsy
Enter fullscreen mode Exit fullscreen mode

It is possible to use the nullish coalescing operator in combination with the traditional AND && and OR || operators, but the statements that include those logical operators must be enclosed in parentheses, or it will raise a syntax error. For example:

null || undefined ?? "value"; // SyntaxError
false || undefined ?? "value"; // SyntaxError

(null || undefined) ?? "value"; // returns "value"
Enter fullscreen mode Exit fullscreen mode

A common pattern is to use the nullish coalescing operator with the optional chaining operator ?., which is useful to access a property of an object which may be null or undefined.

const obj = { prop1: "hello" };

console.log(obj.prop1?.toUpperCase() ?? "error"); // "HELLO"
console.log(obj.prop2?.toUpperCase() ?? "error"); // "error"
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
merkrynis profile image
Julien Bouvet

I discovered it when it was integrated in C#, a few years ago, it changed my life :)