Nullish Coalescing is not as scary as it sounds.
Nullish Coalescing Operator( ?? ) is one of the features of ES2020. It gives the ability to truly check the nullish values. It is another logical operator other than OR ( || ) , AND ( && ) and NOT ( ! ) operators.
How it works?
The operator returns its Right Hand Side (RHS) operand when its Left Hand Side (LHS) operand is null or undefined, otherwise, it will return the LHS operand.
Let's see how it works through some examples:
In the above example, the component Search has a prop
As the prop is an optional one, so the component uses a default value when the prop is undefined. This is the best use-case of Nullish Coalescing operator because the developer doesn't want to restrict component to always have a placeholder for the search input box. So using this an empty string can also be passed for the prop and the component will not use the default value for placeholder and would instead do not show a placeholder string, which can not be accomplished using the logical OR operator.
Below are a few other examples, which will give an idea about more of its use-cases.
Comparison with other similar operators
The operator is similar to logical OR operator and Default Assignment operator. If you would have noticed in the first example, we are just assigning a default value to the prop
searchBoxPlaceholder, which can also be done in the following way:
The above example will no doubt work, but only if the value of prop
searchBoxPlaceholder is undefined. But if the value for a prop is [[null]], then the default assignment will not work.
Also, the logical operator OR works in a similar manner, but it works for all the falsy values. Let us see with the below example what difference comes in the evaluation for the same condition with OR operator.
Now, in the above example, the OR operator serves the purpose of assigning default value, in case the prop is any of the falsy values. But what if the user of the component doesn't want to set any value for the placeholder? The OR operator will not allow doing this, as the empty string ( '' ) is a falsy value. So, now if we use Nullish Coalescing Operator ( ?? ). We can solve this problem and prop can accept an empty string and will not show a placeholder value.
The nullish coalesing operator ( ?? ) is used to assign a default value, against the nullish values (null && undefined).
The operator has a very low prcedence in the MDN Table. It has higher precedence* than Logical AND ( && ) and Logical OR ( || ).
The operator cannot be chained with && and || operators without using any explicit* parentheses.
Check Can I Use for the browser support.
Node JS support start from 14+ version.
That's all for the article. Thanks for reading it. Please comment your feedback and suggestions.