19
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.
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;
which changed to
const name = response?.human?.name;
Now if I have to add a fallback value if name
is not defined to response object
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';
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.
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';
19