DEV Community

anu365
anu365

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.

Problem

As explained in the Optional Chaining Operator we can get properties of an object in a way using Short-Circuit Logic

const name = response && response.human && response.name;
Enter fullscreen mode Exit fullscreen mode

which changed to

const name = response?.human?.name;
Enter fullscreen mode Exit fullscreen mode

Now if I have to add a fallback value if name is not defined to response object

Solution

First thing came to fix this is Short-circuit logic again.
To add a default fallback value using the logical OR operator (||)

const name = response?.human?.name || 'Dev To';
Enter fullscreen mode Exit fullscreen mode

Here the problem arises again.
Name can be Empty value.
Now, Name gives me value as Dev To.

This logic would fail when the left hand side of the OR expression evaluates to falsy (e.g. null, undefined, false, 0, empty string, …), the right hand side of the expression will be used. For null and undefined that’s not a problem, but it is for false, 0, empty string, etc too.

Nullish Coalescing Operator

It serves as an equality check against nullary values (e.g.
null or undefined). Whenever the expression to the left of the ?? operator evaluates to either undefined or null, the value defined to the right will be returned.

const name = response?.human?.name ?? 'Dev To';
Enter fullscreen mode Exit fullscreen mode

Top comments (0)